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
8,000
72,064,465
Why can I not use f-string in the pandas assign method?
<p>For instance, I am trying to create new clean columns in the existing dataframe with a regex pattern applied as shown below. I get the SyntaxError that a keyword can't be an expression.</p> <pre><code>for col in cols2: df.assign(f&quot;{col}_clean&quot;=lambda df:df[col].str.replace(r&quot;\(|\)|,&quot;, &quot;&...
<p><code>df.assign()</code> takes the column names as keyword arguments. You can't use a string as a keyword argument, it has to be an identifier.</p> <p>What you can do is pass a dictionary using <code>**</code> to turn it into keyword arguments.</p> <pre><code>df = df.assign(**{f&quot;{col}_clean&quot;: lambda df:df[...
python|pandas
4
8,001
56,703,423
Custom loss with conditional return value
<p>I want a loss function with this regularization: for each prediction, if the predicted point has norm lower than 0.9 or greater than 1, I want to apply the regularization.</p> <p>So I wrote this:</p> <pre><code>def custom_loss(y_true, y_pred): ret = keras.losses.mean_squared_error(y_true, y_pred) n = tf.norm(y_p...
<p><code>keras.losses.mean_squared_error</code> gives you a scalar number, the mean of all the squared errors. If you want to change the error calculation per example, then do something like this:</p> <pre><code>def custom_loss(y_true, y_pred): diff = tf.squared_difference(y_true, y_pred) n = tf.norm(y_pred, a...
python|tensorflow|keras|loss-function
0
8,002
56,716,948
DECODE_RAW the TensorSliceDataset
<p>I am replicating TTS model, Deep Voice 3. Dataset is LJSpeech-1.1. I found a github repo (<a href="https://github.com/Kyubyong/deepvoice3" rel="nofollow noreferrer">https://github.com/Kyubyong/deepvoice3</a>) but it was written in earlier tensorflow version where I am using TF 2.0. In data processing, I need to ap...
<p>You need to apply parse function to a dataset object. Instead of this line</p> <pre><code>texts = tf.io.decode_raw(texts, tf.int32) # (None,)` </code></pre> <p>use</p> <pre><code>texts = texts.map(lambda x: tf.io.decode_raw(x, tf.int32)) </code></pre>
python|tensorflow|nlp|tensorflow2.0
0
8,003
66,819,359
Build a pytorch model wrap around another pytorch model
<p>Is it possible to wrap a pytorch model inside another pytorch module? I could not do it the normal way like in transfer learning (simply concatenating some more layers) because in order to get the intended value for the next 'layer', I need to wait the last layer of the first module to generate multiple outputs (say...
<p><strong>Yes you can definitely use a Pytorch module inside another Pytorch module.</strong> The way you are doing this in your example code is a bit unusual though, as external modules (<code>VAE</code>, in your case) are more often initialized in the <code>__init__</code> function and then saved as attributes of th...
pytorch
1
8,004
47,088,775
How can I use three Conv1d on the three axis of my 3*n matrix in Pytorch?
<p>The following is my CNN. The input of it is a (3,64) matrix, I want to use three convolution kernels to process the x,y,z axis respectively.</p> <pre><code>class Char_CNN(nn.Module): def __init__(self): super(Char_CNN, self).__init__() self.convdx = nn.Conv1d(1, 12, 20) self.convdy = nn....
<p>The way of convolution is okay. The problem is my labels were between 1 and 13, and the correct range is 0 to 12. After modifying it, my CNN works successfully. But as a fresher to Pytorch and deep learning, I guess my convolution mode can be clearer and easier. Welcome to point out my errors! </p>
deep-learning|pytorch
0
8,005
47,402,346
Ranking groups based on size
<p>Sample Data:</p> <pre><code>id cluster 1 3 2 3 3 3 4 3 5 1 6 1 7 2 8 2 9 2 10 4 11 4 12 5 13 6 </code></pre> <p>What I would like to do is replace the largest cluster id with <code>0</code> and the second largest with <code>1</code> and so on and so forth. Output would be as shown below. </p> <pre><code>id cluste...
<p>The objective is to relabel groups defined in the <code>'cluster'</code> column by the corresponding rank of that group's total value count within the column. We'll break this down into several steps:</p> <ol> <li>Integer factorization. Find an integer representation where each unique value in the column gets its...
python|pandas|numpy|dataframe
4
8,006
68,035,205
Pandas dataframe: grouping by unique identifier, checking conditions, and applying 1/0 to new column if condition is met/not met
<p>I have a large dataset pertaining customer churn, where every customer has an unique identifier (encoded key). The dataset is a timeseries, where every customer has one row for every month they have been a customer, so both the date and customer-identifier column naturally contains duplicates. What I am trying to do...
<p>IIUC use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <code>max</code> for return maximal values per groups and compare with <code>date</code> column, last set <code>1,0</code...
pandas|dataframe|pandas-groupby
0
8,007
68,218,996
List index out of range error using TensorFlow
<p>I am Using TensorFlow to create an image classification model. I have written the following lines of code:</p> <pre><code>import pandas as pd import os import tensorflow as tf import keras from keras.models import Sequential from keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout from keras.preproces...
<p>You are getting error due to the following line</p> <pre><code>dic_label_match[i+1] = str(train_labels.iloc[i][0]) </code></pre> <p>Here you are indexing with 1 instead 0. So when you are executing the following line</p> <pre><code>label_.append(dic_label_match[val]) </code></pre> <p>Your <code>label_</code> has va...
python|tensorflow|keras|deep-learning|image-classification
0
8,008
59,178,619
During Pytorch tutorial a ModuleNotFoundError: ‘pycocotools._mask’ occurs
<p>Hello I’m new to Pytorch and I’ve been trying to work through this tutorial. [<a href="https://github.com/pytorch/tutorials/blob/master/intermediate_source/torchvision_tutorial.rst]" rel="nofollow noreferrer">https://github.com/pytorch/tutorials/blob/master/intermediate_source/torchvision_tutorial.rst]</a></p> <p>I...
<p>The problem is you copied the files for <code>pycocotools</code> instead of installing them. Files ending in <code>.pyx</code> are Cython files which need to be installed into extension modules (on Windows these would be a <code>.pyd</code> file). If you do an installation of the package instead of a file copy that ...
python|python-3.x|visual-studio-code|pytorch|torchvision
0
8,009
57,215,717
how to save a lot of variables with tf.train.Checkpoint
<p>I can save two variables(v1,v2) in checkpoints(<a href="https://www.tensorflow.org/beta/guide/checkpoints#manually_inspecting_checkpoints" rel="nofollow noreferrer">https://www.tensorflow.org/beta/guide/checkpoints#manually_inspecting_checkpoints</a>) with the following way. But if I have many variables(v3,v4 ...), ...
<p>Let me rephrase your question to make sure I understand it correct: "how to save many tf variables in checkpoint?".</p> <p>If it so then my answer would be to put all of those variables into scope and access them in the manner proposed in this answer:<a href="https://stackoverflow.com/a/41642426/11708498">https://s...
python|tensorflow|machine-learning|deep-learning
1
8,010
46,079,186
Tensorflow error when training: Caused by op 'shuffle_batch'
<p>I am trying to read images and labels from a TFRecord file, and then train with these. I know that my TFRecord file exists, and have checked that it does contain 1000 images and labels. My problem only seems to arise when I want to pipe as input to train. I am new to python and tensor flow, and not sure how to fix ...
<p>I moved the initialization to just before the tf.train.start_queue_runners call and that solved the problem i.e. after the model is setup </p> <pre><code>sess.run(tf.local_variables_initializer()) sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord...
python|tensorflow
1
8,011
51,053,396
Convert two tensors with the same values into each other
<p>I have two same tensors in terms of values but they are different in terms of shape like these:</p> <pre><code>output_image1 = [[[[3. 1.] [2. 7.]] [[5. 4.] [9. 8.]]] [[[3. 3.] [1. 4.]] [[6. 5.] [7. 2.]]]] output_image2 = [[[[3] [1] [5] [4]] [[2] [7] [9] [8]] [[3] [3]...
<p>I found the answer, maybe its helpful for others. We should use this function:</p> <pre><code>output_image = tf.depth_to_space( output_image, 2, name=None, data_format='NHWC' ) </code></pre>
python|tensorflow|keras
0
8,012
66,363,025
How to join different pandas dataframes stored on a list of dictionar ordered by multiindex
<p>I have a set of data in a list. Each item of the list is a dictionary with a unique key and the value of the dictionary is a DataFrame that contains 6 columns + index col.</p> <pre><code> list = [{&quot;A&quot;: Participation Assignment Words Creativeness Innovative Great Date ...
<p>First dont use variable <code>list</code>, because python code word (<code>builtin</code>).</p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>, with dictionary is created <code>MultiIndex</code> from keys of dict...
python|pandas|dataframe
0
8,013
66,491,624
Tensorflow 2 Keras Nested Model Subclassing - Total parameters zero
<p>I am trying to implement a simple model subclassing inspired by the VGG network.</p> <p>So here is the code:</p> <pre><code>class ConvMax(tf.keras.Model): def __init__(self, filters=4, kernel_size=3, pool_size=2, activation='relu'): super(ConvMax, self).__init__() self.conv = tf.keras.layers.Con...
<p>The problem is not with keras but in the way you are initializing the layers in <code>RepeatedConvMax</code>.</p> <p>TLDR: don't use <code>vars</code> to dinamically instantiate and retrieve attributes, instead use <code>setattr</code> and <code>getattr</code></p> <p>To solve the problem, you simply have to replace ...
python|tensorflow|keras
3
8,014
66,357,644
Filter pandas columns based on multiple row condition
<p>This is an extension to my earlier question.</p> <p><a href="https://stackoverflow.com/questions/66357241/filter-pandas-columns-based-on-row-condition">Filter pandas columns based on row condition</a></p> <p>Now i want to have multiple conditions to filter columns.</p> <p>Here is my data</p> <pre><code> x1 ...
<p>It should be:</p> <pre><code>x = (pd.to_numeric(df.loc['row2'],'coerce').gt(3)) &amp; (df.loc['row3']=='True') </code></pre> <hr /> <p><strong>x:</strong></p> <pre><code>x1 False x2 False x3 True dtype: bool </code></pre> <p>then you can easily apply filter to get the column where the value is true.</p> <p...
python|pandas|filter
0
8,015
57,537,591
some coordinates that I extracted from geocoder in Python are not saving in the variable I created
<p><code>enter code here</code>Hi, I want to save some coordinates(latitude and longitudes) I extracted through geocodes, the problem I have is those coordinates are not saving and I can't seem to add them as columns to the table I generated using pandas</p> <p>I get this error: AttributeError: 'NoneType' object has n...
<p>The <a href="https://geopy.readthedocs.io/en/stable/#geopy.geocoders.Nominatim.geocode" rel="nofollow noreferrer"><strong><code>nom.geocode(..)</code></strong> [geopy-doc]</a> can result in a <code>None</code> given the address can not be found, or the query is not answered in sufficient time. This is specified in t...
python|pandas|geocode|geopy
1
8,016
51,515,544
Tensorflow faster rcnn giving good detection but still detecting false positives with coco objects
<p>I have used the tensorflow API to detect the Guinness harp using the process described here - <a href="https://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/" rel="nofollow noreferrer">https://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/</a>.</p> ...
<p>I had a similar issue recently, from what it somewhat looks like a case of <strong>underfitting</strong>, I tried multiple things to improve on the results.</p> <p>The thing that worked for me was actually <strong>augmenting data</strong> using the library <strong><a href="https://github.com/aleju/imgaug" rel="nofo...
tensorflow|machine-learning|object-detection-api
1
8,017
51,476,762
get the age from date column in pandas dataframe (Current Date Format : MM/DD/YYYY HH:MM)
<p>How can i get the age from date column in pandas dataframe (Current Date Format : MM/DD/YYYY HH:MM). Age expected in years.</p> <pre><code>ID name dateofbirth 0 Raj 9/17/1966 01:37 1 Joe 11/13/1937 19:20 2 mano 1/5/1964 20:05 3 Rishi 11/13/1937 0:00 </code></pre> <p>i am new to pandas, pl...
<p>This is one approach</p> <pre><code>import pandas as pd import datetime now = datetime.datetime.now() df['dateofbirth'] = pd.to_datetime(df['dateofbirth'], format='%Y-%m-%d_%H:%M:%S') df["Age"] = (now.date() - df['dateofbirth']).astype('&lt;m8[Y]') print(df) </code></pre> <p><strong>Output:</strong></p> <pre><co...
python|pandas|date
2
8,018
70,794,588
CSV - Split multiple-line cell into multiple cells
<p>I’m currently doing some big data work. I have an issue in a .CSV where I need to split a multiple-line single-celled chunk of text, into individual cells. The below table shows the desired output. Currently, all of the 'ingredients' are in the same cell, with each ingredient on its own new line (Stack Overflow w...
<p>Using your code and linked data change delimeter to a comma like below.</p> <pre><code>import pandas as pd df = pd.read_csv('Inventory.csv', delimiter=',') df[&quot;Software&quot;]=df[&quot;Software&quot;].str.split(&quot;\n&quot;) df = df.explode(&quot;Software&quot;).reset_index(drop=True) # Remove rows having e...
python|pandas|dataframe|csv|split
2
8,019
35,819,407
A Simple Network on TensorFlow
<p>I was trying to train a very simple model on TensorFlow. Model takes a single float as input and returns the probability of input being greater than 0. I used 1 hidden layer with 10 hidden units. Full code is shown below:</p> <pre class="lang-python prettyprint-override"><code>import tensorflow as tf import rando...
<p>You are computing only one probability what you want is to have two classes: </p> <ul> <li>greater/equal than zero.</li> <li>less than zero. </li> </ul> <p>So the output of the network will be a tensor of shape two that will contain the probabilities of each class. I renamed y_ in your example to <code>labels</co...
machine-learning|tensorflow|deep-learning
2
8,020
37,313,818
TensorFlow: Dst tensor is not initialized
<p>The <code>MNIST For ML Beginners</code> tutorial is giving me an error when I run <code>print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))</code>. Everything else runs fine. </p> <p>Error and trace:</p> <pre class="lang-py prettyprint-override"><code>InternalErrorTraceback (most rec...
<p>For brevity, this error message is generated when there is not enough memory to handle the batch size.</p> <p>Expanding on <a href="https://stackoverflow.com/users/6416660/steven">Steven</a>'s link (I cannot post comments yet), here are a few tricks to monitor/control memory usage in Tensorflow:</p> <ul> <li>To mo...
tensorflow
36
8,021
37,223,327
Multithreading in Python script
<p>I have few datasets in the form of numpy.arrays, vectors and dictionaries. Let's call them <em>D</em><sub><em>i</em></sub>, <em>i</em> = 1..4. Other than these, I have a csv file F1.csv that has only one column.</p> <p>I have written a python code <strong><em>P</em></strong> that will read rows from F1.csv. For eac...
<p>Not sure if threads can help you with your specific problem but here you go:</p> <pre><code># Code for generating D1 ... # Code for generating D2 ... # Code for generating D3 ... # Code for generating D4 ... # P starts with open('data/F1.csv', 'rb') as csv_file, open('data/F2.csv', 'wb') as F2: F1 = c...
python|multithreading|python-2.7|numpy|scipy
1
8,022
42,084,688
pandas cut and apply: Unexpected behavior for series
<p>For the following dataframe I want to group w.r.t the freq column, bin the data and sum the count data for each bin.</p> <p>Example data look like this</p> <pre><code>df = pd.DataFrame({"freq":[1,2,3], "count": [10,25,3]}) print(df) count freq 0 10 1 1 25 2 2 3 3 </code></pre> <p>To c...
<p>I think <code>apply</code> is not necessary, need only <code>groupby</code> by binned <code>Series</code> which return function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>:</p> <pre><code>print (type(pd.cut(df.freq, bins=[0,1, np.inf...
python|pandas
1
8,023
37,898,617
Having problems feeding data to tensorflow graph
<p>I am trying to adjust the MNIST2 problem in tensorflow tutorial to train a neural network using my own images. But I am having problems feeding data to the graph.</p> <pre><code>My code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path impo...
<p>You are trying to feed the <code>feed_dict</code> argument with TensorFlow tensors. TensorFlow then tries to convert these <code>tf.Tensor</code> to numpy arrays but cannot and returns your error.</p> <p>As you use an input queue, you don't need a <code>feed_dict</code>.</p> <p>Instead of:</p> <pre class="lang-py...
python|numpy|tensorflow|deep-learning
0
8,024
37,800,383
pandas dataframe(DatetimeIndex column) to spark dataframe (datetime format)
<p>I have a python pandas dataframe (pd_df) as follows: </p> <pre><code> time count 0 2015-01-31 835 1 2015-02-28 1693 2 2015-03-31 2439 </code></pre> <p>which I want to convert to spark dataframe (sp_df). I am using the following command : </p> <p>When I tried </p> <p...
<p>Adding here for anyone who had the problem of converting a pandas date column to a spark DateType and not TimeStamp. My df column, although it was a proper <code>dt.date</code> type column in the pandas dataframe, automatically converted to a Spark <code>TimeStamp</code> (which includes the hour 00:00:00). That was ...
python|pandas|apache-spark|pyspark
2
8,025
64,509,819
PatsyError when using statsmodels for regression
<p>I'm using <code>ols</code> in <code>statsmodels</code> to run a regression. Once I run the regressions on each row of my dataframe, I want to retrieve the X variables from <code>patsy</code> thats used in those regressions. But, I get an error that I just cant seem to understand.</p> <p><strong>Edit</strong>: I am t...
<p>The problem is that you're passing a grouped dataframe into the<code>pasty.dmatrices</code> function. Since the grouped dataframe is iterable, you can do it in a loop like this, and store all of your X dataframs (one for each group) into a dictionary:</p> <pre><code>import statsmodels.api as sm import statsmodels.fo...
python|pandas
1
8,026
64,294,776
python numpy.single gives different result when using out parameter
<p>I am trying to cast from a double precision array to single precision. To optimize on space I tried using the out argument so that numpy doesn't allocate additional space. However the results seem different for the two version of the call</p> <pre class="lang-py prettyprint-override"><code>import numpy as np doubl...
<p>This mystery is resolved. Numpy.ctypes when calling c routines creates a bunch of memory for c-python interoperation. This memory doesn't get collected immediately which results in blow up in total memory usage. The solution is to use gc.collect when under memory pressure.</p>
python|numpy|casting|floating-point|precision
0
8,027
58,657,924
unable to convert number to words from Pandas series using num2words python library
<p>I am unable to make a new column in pandas dataframe which converts a number to words using python num2words library, its working using simple int or float parameters but not working with series</p> <p>This is what i have tried:</p> <pre><code>data['words'] = data['Value'].apply(lambda row : num2words(row['Value']...
<p>One way you can accomplish this is by defining a simple function that takes <code>row</code> as input and returns <code>num2words(row['Value'])</code>.</p> <p>Then you can apply it on the DataFrame with <code>axis=1</code>.</p> <pre><code>def f(row): return num2words(row['Value']) data['words'] = data.apply(f...
python|pandas|numpy
0
8,028
58,637,850
Clean and make readable bar graphs on Jupyter Notebook
<p>This might be petty but how can I make my output of bar graphs readable. Apparently I need to remove the <em>+sign</em> on bar heights and also <em>decimals</em> so that I remain with only whole numbers.Here is my data:</p> <pre><code># intialise data of lists. data = {'Hospital_name':['Jootrh Hospital', 'Jootrh H...
<p>Would something like this work for you? I know it is a lot of changes and it is not really in line with my comment, but that is the way I found. I also realise that you may need to tweak a bit to accommodate all the additional dates you have.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import ...
python|pandas|matplotlib|jupyter-notebook
2
8,029
58,607,667
I have written one code in python 2 now i want to execute this in python3, i am getting error
<pre><code>from sqlalchemy import create_engine import pymysql import pandas as pd db='mysql+pymysql://developer:11111@192.168.1.11:3306/pos' db_connection=create_engine(db) df=pd.read_sql_table(table_name='product2', con=db_connection) #df1=pd.read_sql_table(table_name='...
<pre><code>sudo pip3 install sqlalchemy, sudo pip3 install PyMySQL, </code></pre> <p>I installed <code>sqlalchemy</code> and <code>pymysql</code> using these two commands and now I'm not getting any error.</p>
python|pandas|dataframe
0
8,030
58,861,560
Rename column with same column name based on values in DataFrame
<p>I have a DataFrame which can contain columns with the same column name. Based on the value I want to rename the column name so there are no duplicates. I've tried a few things, but every time I try to iterate over the columns and rename them I end up with the column name. df.rename(columns=df.columns[i]: 'some_name'...
<p>Single list comprehension for new column names:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.concat([pd.DataFrame({"A": ['10kg'], "B": ['4']}), pd.DataFrame({"A": ['4%']})], axis=1) df.columns = [c + '_%' if df.applymap(lambda x: '%' in x).any(axi...
python|pandas|dataframe
3
8,031
70,253,399
Write a scipy function without using a standard library (exponential power)
<p>My question might come across as stupid or so simple, but I could not work towards finding a solution. Here is my question: I want to write an exponential power distribution function which is available in scipy. However, I don't want to use the scipy for this. How do I go about it?</p> <p>Here are my efforts so far:...
<p>the simplest way to generate a random number for a given distribution is using the inverse of the CDF of that function, the PPF (Percent point function) will give you the distribution you need when you apply it on uniform distributed numbers.</p> <p>for you case the PPF (taken directly from scipy source code with so...
python|numpy|scipy|statistics|exponential-distribution
0
8,032
70,281,456
How can I set the value of a Series at a specific in a chainable style?
<p>I can't figure how to set the value of a Series at a specific index in a chainable style.</p> <p>For example, say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': [1,2,3], 'b': [0,0,0]}) &gt;&gt;&gt; df a b 0 1 0 1 2 0 2 3 0 </code></pre> <p>If I want to change all the va...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>pandas.Series.where()</code></a> to return a copy of the column with the item at the specified index.</p> <p>This is basically like using <code>.loc</code>:</p> <pre class="lang-py prettyprint-...
python|pandas|method-chaining
1
8,033
70,243,914
Is there a way to obtain all rows/data from paginated json file into pandas dataframe
<p>Edited:</p> <p>Here are my steps:</p> <pre><code>url = &quot;https://ted.europa.eu/api/v2.0/notices/search?&amp;q=TD%3D%5B3%5D&amp;reverseOrder=true&amp;scope=3&amp;sortField=PD&quot; # get data from url response = requests.get(url) # return the json data, and read the output dict keys data = response.json() data...
<p>You should specify the page in your API request. Unfortunately, the API Doc <a href="https://docs.ted.europa.eu/home/index.html" rel="nofollow noreferrer">doesn't seem to be available</a> yet.<br /> However according to this example on <a href="https://github.com/andreas-andersson/TED-api-tool/blob/4b937b4d3a004b2ce...
python|json|pandas|api|pyspark
0
8,034
56,228,711
Error on tensorflow: Shape must be rank 2 but is rank 1 for 'MatMul_25'
<p>I'm trying to create a conditional GAN. However, i'm stuck as to why no matter what i do, it appears the same error over and over again. Here's the code:</p> <pre><code>image_dim = 784 #28 * 28 Y_dimension = 10 gen_hidd_dim = 256 disc_hidd_dim = 256 z_noise_dim =100 #input noise datapoint def xavier_init(shape):...
<p>I think you just missed one call to <code>xavier_init()</code> when initialising your weights.</p> <p>You have this:</p> <pre><code>weights = { 'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])), 'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])), 'gen_H': tf.Variabl...
tensorflow|deep-learning
0
8,035
56,021,933
What is the fastest way to check whether a cell contains letters?
<p>I have a dataset with 2.6 million rows in which I have one column called <code>msgText</code>, which contains written messages.</p> <p>Now, I want to filter out all messages that don't contain any letters. To do so I found the following code:</p> <pre><code>dataset = dataset[dataset['msgText'].astype(str).str.con...
<pre><code>import pandas dataset['columnName'].apply(lambda x: x.find('\\w') &gt; 0) </code></pre>
python|pandas|contains
2
8,036
56,394,146
Add string prefix and string end to dataframe column
<p>I want to add steing prefix and string end to all values of my column of dataframe. In the beginning i want to add <em>r'\b</em> In the end i want to add <em>\b</em> I did This but it doesn't give what i want. A sample of my dataframe is <a href="https://i.stack.imgur.com/BStA3.png" rel="nofollow noreferrer">enter ...
<p>This should be the thing you seek:</p> <pre><code>df['col'] = '\\b' + df['col'] + '\\b' </code></pre> <p>Your <code>r''</code> is only notation that the string is <em>raw</em>.</p>
python-3.x|pandas|dataframe
0
8,037
56,378,206
Why is multiplying matrix by it's inverse with numpy not producing the identity matrix?
<p>I'm multiplying a matrix by it's inverse and not getting an identify matrix in return. My suspicion is there's an issue with the floating point rounding (or lack thereof if the original matrix entries are just ints?) All help is appreciated.</p> <pre><code>C = np.array([[5,5,5],[4,5,6],[7,8,9]]) print("Original ma...
<p>One of the matrix properties say that a matrix only has a inverse form if the determinate of it is different from zero. Your matrix C has zero as determinant, so it does not have a inverse. Numpy make calculation because it does not get zero, but an approximation that in practice is zero.</p> <pre><code>&gt;&gt;&gt;...
python|numpy|matrix
2
8,038
55,850,304
How to pass a Python pandas function as a variable/parameter in another function?
<pre><code>import pandas as pd def func_sum(df, cols, col): res = df[cols].groupby(col).sum() return res def func_count(df, cols,col): res = df[cols].groupby(col).count() return res def func_ave(df, cols, col): res = df[cols].groupby(col).mean() return res </code></pre> <p>The way I did to c...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>groupby.agg</code></a>, which takes one or more functions by reference or by name.</p> <p>For example:</p> <pre><code>def func(df, cols, col, method): return ...
python|pandas
1
8,039
55,578,525
Exit loop in python if SQL query doesn't bring any data
<p>I am new to Python and have been given a task to download data from different Database ( MS SQl and Teradata ). The logic behind my code is as follow : 1: Code picks up data for Vendor from an excel file. 2: From that list it loops through all the vendors and gives out a list of documents. 3: Then I use the list d...
<p>When you are using system resources you should use </p> <pre class="lang-py prettyprint-override"><code>with open(...): </code></pre>
python|pandas|pandasql
0
8,040
55,755,675
Plotting if data is is available at any one time for each station, single plot
<p>As the title suggests, i would like to plot data availability, at any one time for each station. The plot can be thought to be a map or scatter plot, where the station number and time are the coordinates. Which will plot vertical lines, where there is data (i.e. floats/integers), and as a white space if data is miss...
<p><strong>Updated</strong>: I have updated this answer according to the comments</p> <p>Ok, so first of all, your input data is a bit messed up, with the delimiter actually being tabs (<code>'\t'</code>) and the first column rather ending in <code>,</code> instead. </p> <p>Important steps:</p> <ul> <li>take care of...
python|r|pandas|matplotlib
1
8,041
64,729,078
How to generate a dataframe from lists of separate variables
<p>I have asked the same question here: <a href="https://stackoverflow.com/questions/64723083/convert-lists-from-separate-variables-into-a-dataframe">Convert lists from separate variables into a dataframe</a> which was closed.</p> <p>The suggestions provided do not answer my question because what I have is not a list o...
<p>Use <code>df.to_csv()</code>:</p> <pre><code>import pandas as pd a=[1.4, 1.3] b=[0.8, 0.8] c=[2.4, 1.6] d=[3.6, 2.9] e=[2.8, 2.5] df = [a,b,c,d,e] df = pd.DataFrame(df, columns=['column_1', 'column_2']) print(df.to_csv(index=False)) </code></pre> <p>Output:</p> <pre><code>column_1,column_2 1.4,1.3 0.8,0.8 2.4,1.6 3...
python|pandas|dataframe
2
8,042
64,770,251
Pandas Merge Multiple Columns
<p>I am struggling to merge two pandas dataframes to replicate a vlookup function using two columns as lookup value.</p> <p>The first dataframe df has 6 columns including three columns: perf, ticker and date. The perf column is empty and this is the one I would like to see populated. The second dataframe u includes the...
<p>If the <code>'perf'</code> column is empty in the first DataFrame, may I suggest removing it before merging the two DataFrames?</p> <pre><code>df=pd.merge( df.drop(columns='perf'), u, how='left', on=['ticker_and_exch_code', 'date'], ) </code></pre>
python|pandas|dataframe|merge
1
8,043
40,058,912
randomly controlling the percentage of non zero values in a matrix using python
<p>I am looking to create matrices with different levels of sparsity. I intend to do that by converting all the values that are nonzero in the data matrix to 1's and the remaining entries would be 0.</p> <p>I was able to achieve that using the following code. But I am not sure how would I be able to randomly make the ...
<p>You could do something like this -</p> <pre><code>idx = np.flatnonzero(a) N = np.count_nonzero(a!=0) - int(round(0.25*a.size)) np.put(a,np.random.choice(idx,size=N,replace=False),0) </code></pre> <p><strong>Sample run</strong></p> <p>1) Input array :</p> <pre><code>In [259]: a Out[259]: array([[0, 1, 0, 1, 1], ...
python|python-3.x|numpy|matrix|scipy
0
8,044
39,966,543
ValueError: If using all scalar values, you must pass an index
<p>Take the following code:</p> <pre class="lang-py prettyprint-override"><code>import MySQLdb as mdb import pandas as pd con = mdb.connect(db_host, db_user, db_pass, db_name) query = """SELECT `TIME`.`BID-CLOSE` FROM `EUR-USD`.`tbl_EUR-USD_1-Day` WHERE TIME &gt;= '2006-12-15 22:00:00' AND TIME &...
<p>The problem is that when you use the <code>DataFrame</code> constructor:</p> <pre><code>pd.DataFrame({m: eurusd.interpolate(method=m) for m in methods}) </code></pre> <p>the value for each <code>m</code> is a <code>DataFrame</code>, which will be interpreted as a scalar value, which is admittedly confusing. This c...
python|pandas|quantitative-finance
7
8,045
39,676,294
Looping over files and plotting (Python)
<p>My data is look like as in the picture. All of my datas are in .txt format and my aim is to loop over files and plot them. First row represents my variables (WL, ABS, T%) so firstly I need to delete them before proceeding. </p> <pre><code>with open('Desktop/100-3.txt', 'r') as f: data = f.read().splitlines(True) w...
<p>For data files like this I would prefer <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">np.genfromtxt</a> over np.loadtxt, it has many useful options you can look up in the docs. The <a href="https://docs.python.org/3/library/glob.html" rel="nofollow">glob</a> modul...
python|numpy|plot
2
8,046
39,729,508
Colored 3D plot
<p>I found here this good <a href="https://stackoverflow.com/questions/12423601/python-the-simplest-way-to-plot-3d-surface">example</a> to plot 3D data with Python 2.7.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import cm from mpl_toolkits.mplot3d import Ax...
<p>As mentioned in the comment, you can use a contour. Since you are already using a triangulation, you can use <code>tricontourf</code>. See an example below.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np ## data: DATA = np.array([ [-0.807237702464, 0.904373229492, 111.428744443], [-0....
python|numpy|matplotlib|mplot3d
3
8,047
39,479,919
How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?
<p>I am using Python3.5 and I am working with pandas. I have loaded stock data from yahoo finance and have saved the files to csv. My DataFrames load this data from the csv. This is a copy of the ten rows of the csv file that is my DataFrame</p> <pre><code> Date Open High Low Close Volume A...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html" rel="noreferrer">pct_change()</a> or/and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="noreferrer">diff()</a> methods</p> <p>Demo:</p> <pre><code>In [138]: df....
python|pandas|numpy|dataframe|indexing
66
8,048
44,052,719
Slow loading of large NumPy datasets
<p>I notice a long loading time (~10 min) of a .npy file for a 1D numpy array of object data type and with a length of ~10000. Each element in this array is an ordered dictionary (OrderedDict, a dictionary subclass from collections package) with a length ~5000. So, how can I efficiently save and load large NumPy arrays...
<p>Numpy will pickle embedded objects by default (which you could avoid with <code>allow_pickle=False</code> but sounds like you may need it) which is slow (see <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/n...
python|arrays|numpy|ordereddictionary
2
8,049
44,136,451
Use python pandas or R, organize calendar data
<p>I have a data frame that records employees' attendance history and it looks like the following:</p> <pre><code>ID Sunday Monday Tuesday Wednesday Thursday Friday Saturday 1585 NA NA NA NA NA NA NA 1585 NA S S S S H NA 1585 NA H ...
<p>Based on the idea of @Cholts, I write a R code for generating the desired output</p> <pre><code>#clean the workspace rm(list=ls(all=TRUE)) require(tidyr) library(dplyr) library(lubridate) library(stringr) ID = c(rep(1585,4),rep(1597,4)) Sun = c(rep("D",8)) Sat = c(rep("D",8)) Mon = c("Y","S","H","S","S","Y","H","Y...
python|r|pandas|tidyr
1
8,050
69,547,137
How should I avoid duplicate imports when writing a package?
<p>I'm making a python package to run analyses with pandas, and I use pandas objects in most files in the package. How do I import those functions so they're usable in the package but don't clutter the namespace for a user? Say I have this directory structure:</p> <pre><code>MyThing/ MyThing/ __init__.py ...
<p>What you are doing is fine and how it's supposed to work and I wouldn't advise trying hard to hide your pandas import.</p> <p>The solution to this <code>df = mt.apis.pd.DataFrame()</code> is: don't do that.</p> <p>If there is a function or variable within <code>Mything.apis</code> that you don't want others to use, ...
python|pandas|dataframe
1
8,051
69,529,353
Remove rows from X_train and y_train at once
<p>I'm absolutely new in python, so there is a question.</p> <p>I've splitted my original df to X_train, y_train, X_test, y_test. Now i want to drop from y_train (pd.series) outliers therefore i need to remove object with same index from X_train(pd.df). What is the easiest and cleanest way to do it?</p>
<p>try using <code>y_train = y_train[X_train_new.index]</code> where <code>X_train_new</code> is your new <code>X_train</code> after dropping some columns/row/outliers.</p>
python|pandas|scikit-learn
0
8,052
69,604,098
Python dataframe transpose time series (rows to column)
<p>I would like to transpose (?)/ transfrom this time series:</p> <pre><code>values = ['Date Value Value_30days_later', '26.01.01 36 40.3', '29.01.01 36 38.2', '30.01.01 37.5 36.5', '31.01.01 37.5 37.3', '01.02.01 37 36.7', '02.02.01 37.5 36.5', '05.02.01 35 33', '06.02.01 32.5 26.5', ...
<p>I got it now by using this function</p> <pre><code> def create_lags(): for lags in range(0,5): time_series['value_lag_-'+str(lag)] = time_series['value'].shift(+lag) </code></pre> <p>This <strong>.shift function</strong> does it for me.</p>
python|pandas|dataframe|numpy
0
8,053
69,530,356
How to calculate a mean from a range of rows
<p>Using a forloop, how do I calculate 5 sets of data to calculate for example the mean and standard deviation?</p> <p>For example the array is</p> <pre class="lang-py prettyprint-override"><code>data = np.array([[49, 32, 32, 8, 49], [ 1, 29, 28, 45, 20], [11, 40, 5, 6, 21], ...
<p>You can do it quite easily without for loop like the following:</p> <pre><code>import numpy as np data = np.array([[49, 32, 32, 8, 49], [ 1, 29, 28, 45, 20], [11, 40, 5, 6, 21], [13, 45, 3, 12, 12], [11, 6, 39, 39, 27], [10, 3...
python|numpy|for-loop
0
8,054
69,482,711
How to determine cycles with Pandas
<p>Based on sample dataframe:</p> <pre><code>import pandas as pd Machine = [0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0] df2 = pd.DataFrame(Machine) </code></pre> <p>This is mocking a machine being on and off. 0 means that it is off, and 1 ...
<p>It's maybe not the best way, but you can build something like:</p> <pre><code>df['error_n-2'] = df['Machine'].eq(df.col1.shift(-2)) df['error_n-1'] = df['Machine'].eq(df.col1.shift(-1)) df['error_n+1'] = df['Machine'].eq(df.col1.shift(1)) df['error_n+2'] = df['Machine'].eq(df.col1.shift(2)) df['nb_diff'] =df['erro...
python|pandas
0
8,055
53,853,899
How to create a column timestamp while using apply in a pandas dataframe?
<p>I am applying some functions to pandas dataframe columns as:</p> <pre><code>def foo(x): return 1 + x </code></pre> <p>Then, I apply the function to a column:</p> <pre><code>df['foo'] = df['a_col'].apply(foo) </code></pre> <p>How can I return a column with the amount of miliseconds that the function <code>fo...
<p>You can use the <code>time</code> module. Given you also wish to create a new series via a calculation, you can output a sequence of tuples, then convert to a dataframe and assign back to two series.</p> <p>Here's a demonstration:</p> <pre><code>import time df = pd.DataFrame({'A': [2, 4, 4, 3, 4]}) def foo(x): ...
python|python-3.x|pandas|time
2
8,056
54,211,955
Build JSON object from pandas dataframe
<p>I'm trying to format pandas dataframe:</p> <pre><code>&gt; year mileage model manufacturer power fuel_type price &gt; 0 2011 184000 c-klasa Mercedes-Benz 161 diesel 114340 &gt; 1 2013 102000 v40 Volvo 130 diesel 80511 &gt; 2 2014 191000 scenic Renault 85 diesel 57613 &gt; 3 1996 210000...
<p>I believe you need create Series by <code>unique</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.unique.html" rel="nofollow noreferrer"><code>SeriesGroupBy.unique</code></a> and then convert to json by <a href="http://pandas.pydata.org/pandas-docs/sta...
python|json|python-3.x|pandas|dictionary
1
8,057
54,198,577
ValueError: Cannot feed value of shape (1, 4, 84, 84) for Tensor 'Placeholder:0', which has shape '(?, 84, 84, 4)'
<p>I am running a DQN to learn to play Atari games, and am training it on GPU. I noticed that the 'data_format' for my model was NHWC (which is slower than NCHW for GPU training). I changed the data_format to NCHW but it gave this error;</p> <pre><code>ValueError: Cannot feed value of shape (1, 4, 84, 84) for Tensor '...
<p>From your code:</p> <blockquote> <p><code>X_state = tf.placeholder(tf.float32, shape=[None, input_height, input_width, input_channels])</code></p> </blockquote> <p>You're hardcoding the shape of the placeholder to be in the NHWC format. If you want to feed arrays in NCHW format, change <code>X_state</code> to <c...
python|tensorflow|deep-learning|reinforcement-learning|openai-gym
1
8,058
38,508,294
How to get the max/min value in Pandas DataFrame when nan value in it
<p>Since one column of my pandas dataframe has <code>nan</code> value, so when I want to get the max value of that column, it just return error. </p> <pre><code>&gt;&gt;&gt; df.iloc[:, 1].max() 'error:512' </code></pre> <p>How can I skip that <code>nan</code> value and get the max value of that column?</p>
<p>You can use <code>NumPy</code>'s help with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmax.html" rel="noreferrer"><code>np.nanmax</code></a>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmin.html" rel="noreferrer"><code>np.nanmin</code></a> :</p> <pre><code>In [28]...
python|pandas
19
8,059
66,325,217
Upload data from DICOM files in Torchvision Model
<p>I'm sorry if the question is too basic, but I am just getting started with PyTorch (and Python).</p> <p>I was trying to follow step by step the instructions here: <a href="https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/begin...
<p>It sounds like you will be better off implementing your own <a href="https://stackoverflow.com/a/64574689/1714410">custom <code>Dataset</code></a>. And indeed, I think it would be better deferring normalization and other stuff to the transformations applied just before reading the images for the model.</p>
python|pytorch|torchvision|pydicom|medical-imaging
0
8,060
66,000,662
How to replace a string in a column based on the value of another column?
<p>I have this dataframe:</p> <pre><code>df = pd.DataFrame([['US123','1111'],\ ['CA456', '2222'],\ ['US123', '3333'],\ ['US123','4444'], \ ['CA456', '5555']], columns=['ID', 'Notes']) df </code></pre> <p><a href="https://i.stack.imgur.com/mDcip...
<p>You may use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>, that'll change column <code>Notes</code> only where needed, based on the condition on the <code>ID</code> column</p> <pre><code>df.loc[df['ID'].str.star...
python|pandas
2
8,061
66,327,985
Combining is in and where
<p>How can I create new column based on the odd even flag in Pandas</p> <p>This is my data:</p> <pre><code>id Flag 001 1 002 2 003 3 004 4 </code></pre> <p>I would like to have this output if flag is even number then female, if flag is odd number then male:</p> <pre><code>id Flag Gender 001 1 Male ...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with modulo <code>2</code> for check even and odd numbers:</p> <pre><code>df['Gender'] = np.where(df['Flag'] % 2,'Male','Female') print (df) id Flag Gender 0 1 1 Male 1...
python|pandas|numpy|combinations|where-clause
1
8,062
66,037,882
Is there a way to resample price data to OHLC without trading out the DateTime Index for a RangeIndex?
<p>So I'm in a bit of a pickle.</p> <p>I want to resample time and price ticker data into Open High Low Close.</p> <p>To do that first I use <code>df.date = pd.to_datetime['date']</code> followed by <code>df = df.set_index('date')['price'].resample('1H').ohlc()</code></p> <p>However in the process I lose my precious df...
<p>In fact, you can use the <a href="https://stackoverflow.com/questions/66002493/attributeerror-while-trying-to-resample-a-pandas-dataframe-with-datetimeindex/66002616#66002616">method2</a> I mention before.</p> <pre><code># method2 df['hr'] = pd.to_datetime(df['date'].dt.strftime('%Y-%m-%d %H:00')) dfn = df.join(df.g...
python|pandas|dataframe|datetime|matplotlib
1
8,063
66,215,723
Issue using a variable with an r-string in Python
<p>Fairly new to Python, and I've got a batch job that I now have to start saving some extracts from out to a company Sharepoint site. I've searched around and cannot seem to find a solution to the issue I keep running into. I need to pass a date into the filename, and was first having issues with using a normal stri...
<p>Per the comment from @Matthias, as it turns out, an r-string can't end with a single backslash. The quick workaround, therefore, was:</p> <pre><code>x = r&quot;\\mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts&quot; + &quot;\\&quot; </code></pre> <p>The comment from @sammywemmy also linked to what look...
python|pandas
0
8,064
66,235,161
Apply function to every two columns in dataframe and replace original columns with output
<p>I have a dataframe that contains X &amp; Y data in columns like this:</p> <pre><code>df_cols = ['x1', 'y1', 'x2', 'y2', 'x3', 'y3'] np.random.seed(365) df = pd.DataFrame(np.random.randint(0,10,size=(10, 6)), columns=df_cols) x1 y1 x2 y2 x3 y3 0 2 4 1 5 2 2 1 9 8 4 0 3 3 2 7 7 ...
<p>Use slicing and apply operations on those slices.</p> <pre><code>def samplefunc(x, y): x = x**2 y = y/10 return x, y arr = df.to_numpy().astype(object) e_col = arr[:, ::2] o_col = arr[:, 1::2] e_col, o_col = samplefunc(e_col, o_col) arr[:, ::2] = e_col arr[:, 1::2] = o_col out = pd.DataFrame(arr, co...
python|pandas|dataframe|numpy
1
8,065
52,753,613
Grouping / Categorizing ages column
<p>I have a dataframe say <code>df</code>. <code>df</code> has a column <code>'Ages'</code></p> <p><code>&gt;&gt;&gt; df['Age']</code></p> <p><a href="https://i.stack.imgur.com/pcs2l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pcs2l.png" alt="Age Data"></a></p> <p>I want to group this ages and create a...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="noreferrer"><code>pandas.cut</code></a> with parameter <code>right=False</code> for not includes the rightmost edge of bins:</p> <pre><code>X_train_data = pd.DataFrame({'Age':[0,2,4,13,35,-1,54]}) bins= [0,2,4,13,20,110] label...
python|pandas|dataframe
25
8,066
46,334,814
Replacing values in a list of Numpy arrays
<p>Let's say I have a list of Numpy arrays with varying shapes and need to replace all values of 255 with 1. </p> <pre><code>A = np.array([[0,255], [0,0]]) B = np.array([[0, 255,255], [255,0,0]]) list_of_array = [A, B] # list could have many more arrays </code></pre> <p>Methods like <code>np.place()</code> and <code...
<p>If you have to have a list of arrays, and want to modify the values in those arrays rather than creating new ones, then you can do it by iterating over the list.</p> <pre><code>import numpy as np A = np.array([[0,255], [0,0]]) B = np.array([[0, 255,255], [255,0,0]]) list_of_array = [A, B] # list could have many m...
python|numpy
2
8,067
46,211,631
Python, Cv2, numpy to indicate areas in a picture/image
<p>I want to specify certain areas in an image.</p> <p>To specify 1 area I can do this:</p> <pre><code>import cv2 import numpy as np the_picture = cv2.imread("c:\\picture.jpg") target_area = the_picture[300:360, 130:280] </code></pre> <p>The type of target_area is type 'numpy.ndarray'.</p> <p>But a list of coordi...
<p>If I understood correctly what you want to do, and please correct me if I'm wrong, you could solve your problem by saving and retrieving the area coordinates as individual values, and not as pairs</p> <pre><code>the_picture = cv2.imread("c:\\picture.jpg") list_of_areas = [ [300, 360, 130, 280], [300, 360, 440, 540...
python|image|opencv|numpy
2
8,068
46,261,671
Use numpy setdiff1d keeping the order
<pre><code>a = np.array([1, 2, 3]) b = np.array([4, 2, 3, 1, 0]) c = np.setdiff1d(b, a) print("c", c) </code></pre> <p>The result is <code>c [0, 4]</code> but the answer I want is <code>c [4 0]</code>.</p> <p>How can I do that?</p>
<p>Get the mask of non-matches with <code>np.in1d</code> and simply boolean-index into <code>b</code> to retain the order of elements in it -</p> <pre><code>b[~np.in1d(b,a)] </code></pre> <p>Sample step-by-step run -</p> <pre><code>In [14]: a Out[14]: array([1, 2, 3]) In [15]: b Out[15]: array([4, 2, 3, 1, 0]) In...
python|numpy
10
8,069
58,585,241
modify the x-axis labels in histogram plot using matplotlib
<p>I use the following code to plot the histogram. If I want to make the label along the x-axis more fine grained, how to change the code. For instance, the current plot segment the x-axis with 0.2 as interval, can I have 0.05 as interval?</p> <pre><code>import matplotlib.pyplot as plt plt.hist(image_pixel_array,bins=...
<p>Here,</p> <pre><code>plt.xlim([-3, 3]) plt.ylim([-3, 3]) plt.yticks(np.arange(-3, 3, 0.5)) plt.xticks(np.arange(-3, 3, 0.5)) plt.show() </code></pre> <p>you'll get the ticks 0.5 distance apart in the range of -3 to 3. Hope this helps.</p>
python|python-3.x|numpy|matplotlib|scipy
5
8,070
58,175,304
Which Normalization method, min-max or z-scaling (Zero mean unit variance), works best for deep learning?
<p>I have data that is representing relative counts (0.0-1.0) as presented in the example below. calculated with the formula </p> <pre><code>cell value(E.g.23)/sum of the colum(E.g. 1200) = 0.01916 </code></pre> <p>Example data </p> <pre><code> f1 f2 f3 f5 f6 f7 f8 class ...
<p>z-scaling is a good idea when your data is approximately normally distributed, this can often be the case.</p> <p>min-max scaling is the right thing to do when you expect a largely uniform distribution.</p> <p>In short, it depends on your data and your neuronal network.</p> <p>But both are sensitive to outliers, ...
machine-learning|deep-learning|normalization|tensorflow-datasets
0
8,071
58,466,368
Logistic Regression - How to use model on another dataset and get probability values
<p>I'm making my first ML model and I need some help with using model on second dataset.</p> <p>So I have two sets: "train_full.csv" and "test_full.csv". Both sets have the exact same structure.</p> <p>Only difference is that in "train_full.csv" column "target" is filled with 0s and 1s and in "test_set.csv" this colu...
<p>It is pretty simple.</p> <p>You just need to drop the target column from the <code>test_set</code> and need to use <code>logmodel.predict()</code> for classification and <code>logmodel.predict_proba()</code> for probability. Here is an example for the same =&gt;</p> <pre><code>test_set = test_set.drop(['target'],axi...
python|pandas|machine-learning|scikit-learn|logistic-regression
0
8,072
69,236,479
Using python generators with lots of data
<p>I have a dataset consisting of 250k items that need to meet certain criteria before being added to a list/generator. To speed up the processing, I want to use generators, but I am uncertain about whether to filter the data with a function that yields the filtered sample, or if I should just return the filtered sampl...
<p>The short answer is that none of these are best. Numpy and pandas include a lot of C and Fortan code that works on hardware level data types stored in contiguous arrays. Python objects, even low level ones like <code>int</code> and <code>float</code> are relatively bulky. They include the standard python object head...
python|pandas|performance|generator
1
8,073
44,776,682
How to efficiently sum and mean 2D NumPy arrays by id?
<p>I have a 2d array <code>a</code> and a 1d array <code>b</code>. I want to compute the sum of rows in array <code>a</code> group by each id in <code>b</code>. For example:</p> <pre><code>import numpy as np a = np.array([[1,2,3],[2,3,4],[4,5,6]]) b = np.array([0,1,0]) count = len(b) ls = list(set(b)) res = np.zeros(...
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow noreferrer">numpy_indexed</a> package (disclaimer: I am its author) was made to address problems exactly of this kind in an efficiently vectorized and general manner:</p> <pre><code>import numpy_indexed as npi unique_b, mean_a = np...
python|arrays|numpy
3
8,074
61,167,421
Split pandas list to different column and calculate the counts
<p>I've a pandas dataframe with a column name <code>ids</code> that contains list elements. So I want to split the <code>list</code> column to different columns.</p> <pre><code>id partner_id ids 1 12 ["1","4","187275","187358","946475"] 2 12 ...
<p>I think you are close, only is used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a> for append to original, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofol...
python|pandas
3
8,075
60,863,574
how to check if tenserflow is using gpu?
<p>I am using Jupyter notebook for training neural network. I choose in the anaconda applications on tenserflow-gpu however I dont think it is using GPU. How can I check it if it is using GPU for processing? </p>
<p>You could use the </p> <pre><code>&lt;tf.config.list_physical_devices('GPU')&gt; </code></pre> <p>For tensorflow 2.1. Also check the documentation found <a href="https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices" rel="nofollow noreferrer">here</a></p>
tensorflow|deep-learning|gpu
2
8,076
71,778,511
How to count word similarity between two pandas dataframe
<p>Here's my first dataframe <code>df1</code></p> <pre><code>Id Text 1 Asoy Geboy Ngebut 2 Asoy kita Geboy 3 Bersatu kita Teguh </code></pre> <p>Here's my second dataframe <code>df2</code></p> <pre><code>Id Text 1 Bersatu Kita 2 Asoy Geboy Jalanan </code></pre> <p>Similarity Matrix, columns is <code...
<p>IIUC, you need to compute a <code>set</code> intersection:</p> <pre><code>l1 = [set(x.split()) for x in df1['Text'].str.lower()] l2 = [set(x.split()) for x in df2['Text'].str.lower()] pd.DataFrame([[len(s1&amp;s2)/len(s1) for s1 in l1] for s2 in l2], columns=df1['Id'], index=df2['Id']) </code></pre> <p...
python|pandas|dataframe|text|cosine-similarity
1
8,077
71,471,838
Get rid of iterrows in pandas loop
<p>I'm trying to avoid using <code>iterrows()</code> in pandas and achieve a more performant solution. This is the code I have, where I loop through a DataFrame and for each record I need to add three more:</p> <pre><code>import pandas as pd fruit_data = pd.DataFrame({ 'fruit': ['apple','orange','pear','orange'],...
<p>You could use <code>repeat</code> to repeat each fruit 3 times; then <code>groupby</code> + <code>cumcount</code> to assign <code>sequence</code> numbers; finally <code>to_dict</code> for the final output:</p> <pre><code>tmp = fruit_data['fruit'].repeat(3).reset_index(name='fruit_2') tmp['sequence'] = tmp.groupby('i...
python|pandas|dataframe
1
8,078
42,337,793
Supress printing of pandas output to console
<p>I am using <code>topic_.set_value(each_topic, word, prob)</code> to change the value of cells in a pandas dataframe. Basically, I initialized a numpy array with a certain shape and converted it to a pandas dataframe. I am then replacing these zeros by iterating over all the columns and rows using the code above. The...
<p>just redirect the output into variable:</p> <pre><code>&gt;&gt;&gt; df.set_value(index=1,col=0,value=1) 0 1 0 0.621660 -0.400869 1 1.000000 1.585177 2 0.962754 1.725027 3 0.773112 -1.251182 4 -1.688159 2.372140 5 -0.203582 0.884673 6 -0.618678 -0.850109 &gt;&gt;&gt; a=df.set_value(index=1,...
python|pandas
1
8,079
69,818,184
Loop over column to verify condition and change cell values when need it with pandas
<p><a href="https://i.stack.imgur.com/Xjbla.png" rel="nofollow noreferrer">Pandas Data Frame</a>, I would like to loop over the column named 'first' to verify if is an email or not, if is an email remove it and leave that cell blank.</p> <p>I have try</p> <pre><code>for x in df['first']: if '.com' in x: x...
<p>Answering the <code>pandas</code> portion of this, since that's not exactly email verification.</p> <p>Use <code>.map</code> with a <code>lambda</code> function for this. This is the preferred way to do what you are trying to do in pandas, instead of iterating.</p> <pre class="lang-py prettyprint-override"><code>df[...
python|pandas
1
8,080
72,174,008
How to change "printed list" into dataframe with python
<p>I would like to convert my &quot;printed list&quot; into a dtaframe:</p> <p>1st: I import a lift of tickers/symbols from a folder import yfinance as yf</p> <pre><code>with open(&quot;/Users/AB/OD/Earnings/tickers.txt&quot;) as fh: tick1 = fh.read().split() </code></pre> <p>(here is an example of ticker to be sav...
<ol> <li>Before loop you could create list.</li> <li>Inside loop you could append to this list</li> <li>After loop you could convert this list to DataFrame</li> </ol> <p>And converting depends on what type of data you get in <code>marketCap</code> - <code>pandas.DataFrame</code>, <code>pandas.Series</code>, <code>list<...
python|pandas|list|dataframe
1
8,081
50,667,577
Tensorflow: tf.rnn.raw_rnn - fn_loop not callable?
<p>I try to use a custom function for the loop_fn in an raw_rnn but there is this weird</p> <pre><code>"raise TypeError("loop_fn must be a callable")" # Exception thrown? </code></pre> <p>Call:</p> <pre><code>callable_loop_fn = loop_fn( time=time, previous_output=None, previous_state=None, previous_...
<p><code>callable_loop_fn</code> is not a function, therefore it is not callable. </p> <p>Specifically, <code>callable_loop_fn</code> is the value returned by <code>loop_fn()</code> which, in turn, returns either the output of <code>loop_fn_initial()</code> or the output of <code>loop_fn_initial()</code>. Evidently, n...
tensorflow|python-3.6|rnn|callable
2
8,082
50,388,396
error name 'dtype' is not defined
<p>I try to compile this code but I get this errror : </p> <pre><code>NameError: name 'dtype' is not defined </code></pre> <p>Here is the python code : </p> <pre><code># -*- coding: utf-8 -*- from __future__ import division import pandas as pd import numpy as np import re import missingno as msno from functools impo...
<p>You should use <code>type</code> instead of <code>dtype</code>.</p> <p><code>type</code> is a built-in function of python - <a href="https://docs.python.org/3/library/functions.html#type" rel="nofollow noreferrer">https://docs.python.org/3/library/functions.html#type</a></p> <p>On the other hand, If <code>data</co...
python|numpy
3
8,083
50,664,839
Format Excel Column header for better visibility and Color
<p>I have gone through many posts but did not found the exact way to do the below. Sorry for attaching screenshot(Just for better visibility) as well , I will write it also. Basically it looks like -</p> <pre><code>Name_of_the_Man Address_of_Man City Jordan NC LMN </code></pre> <p>Input csv lo...
<p>You can use <a href="http://xlsxwriter.readthedocs.io/example_pandas_header_format.html" rel="noreferrer">Pandas Excel output with user defined header format</a> with <a href="https://stackoverflow.com/a/36554382/2901002">solution</a> for change width by content:</p> <pre><code>writer = pd.ExcelWriter("file.xlsx", ...
python|excel|python-3.x|pandas|csv
10
8,084
50,301,544
How to delete columns without headers in python pandas read_csv
<p>Currently, I have to read the CSV file and set the headers in advance. And then drop the columns which I don't want. Is there any way to do this directly?</p> <pre><code># Current Code columns_name = ['station', 'date', 'observation', 'value', 'other_1', 'other_2', 'other_3', 'other_4'] del_columns_name = ['other_...
<p>I think you might even specify the indexes right away. In this case you are insterested in: <code>[0,1,2,3]</code>. Consider this example which also parses dates.</p> <pre><code>import pandas as pd cols = ['station', 'date', 'observation', 'value'] data = '''\ 1, 2018-01-01, 1, 1, 1, 1, 1, 1 2, 2018-01-02, 2, 2, ...
python|python-3.x|pandas|dataframe
2
8,085
62,664,384
How do I swap the duplicates in a row with a blank without affecting the corresponding rows using python?
<p>Let's say we have the following data on excel,</p> <pre><code>Column1 | Column2 | Column3 | .... Column n A | 10 | a A | 10 | b A | 10 | c B | 15 | d B | 15 | e B | 15 | f C | 20 | g C | 20 | h . ...
<p>You can first find the indices of the duplicates</p> <p><code>dup_index = df.duplicates().index</code></p> <p>Then you can replace the values</p> <p><code>df.Column1.replace(dup_index,'')</code></p> <p>If you don't want blank values as rchurt said in the comment , groupby() can also be a good option if you don't wan...
python|pandas|duplicates
1
8,086
62,728,659
mse loss function not compatible with regularization loss (add_loss) on hidden layer output
<p>I would like to code in tf.Keras a Neural Network with a couple of loss functions. One is a standard mse (mean squared error) with a factor loading, while the other is basically a regularization term on the output of a hidden layer. This second loss is added through <code>self.add_loss()</code> in a user-defined cla...
<p>I stuck with the same problem for a few days. &quot;Standard&quot; loss is going to be a scalar at the moment when we add it to the loss from add_loss. The only way how I get it working is to add one more axis while calculating mean. So we will get a scalar, and it will work.</p> <pre><code>tmp = self.rate*K.mean(in...
python-3.x|neural-network|layer|tf.keras|tensorflow2.x
2
8,087
62,593,523
How to populate value in column based on condition using numpy?
<p>Hi I am trying to populate new column with fixed value, if condition is met. But i am also getting the value if condition is not met.(for some rows) Where am i going wrong ? I need blank in 'type' if 'id' is blank, else the string 'A2A' datatype of column'ID1' is object. It gives error when i convert it into string....
<p>you can try this:</p> <p>Make sure you remove multiple empty spaces to just empty</p> <pre><code>df = pd.DataFrame([None, np.nan, '','','',2,3,'','']) df = df.replace(r'^\s*$', '', regex=True) df.fillna('', inplace=True) </code></pre> <p><strong>Option 1: You can use pandas <code>.apply</code></strong></p> <pre><co...
python|pandas|numpy
1
8,088
62,794,219
tensorflow GPU not showing in jupyter notebook
<h2>In terminal</h2> <ul> <li>windows 10</li> <li>using cuda 10.1</li> <li>python 3.7.7</li> <li>GPU GeForce GTX 1050 4GB</li> </ul> <pre class="lang-sh prettyprint-override"><code>&gt;&gt;&gt; import tensorflow as tf 2020-07-08 17:10:50.005569: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successful...
<p>It needs to make new kernel for this env and select kernel form jupyter notebook</p> <pre class="lang-sh prettyprint-override"><code>$ conda activate env_name $ pip install ipykernel --user $ python -m ipykernel install --user --name env_name --display-name env_name </code></pre>
python|tensorflow|jupyter-notebook
0
8,089
73,610,869
The expanded size of the tensor (1011) must match the existing size (512) at non-singleton dimension 1
<p>I have a trained a LayoutLMv2 model from huggingface and when I try to inference it on a single image, it gives the runtime error. The code for this is below:</p> <pre><code>query = '/Users/vaihabsaxena/Desktop/Newfolder/labeled/Others/Two.pdf26.png' image = Image.open(query).convert(&quot;RGB&quot;) encoded_inputs ...
<p>The error message tells you that the extracted text via ocr is longer (1011 tokens) than the underlying text model is able to handle (512 tokens). Depending on your task, you maybe can truncate your text with the tokenizer parameter <a href="https://huggingface.co/docs/transformers/main/en/model_doc/layoutlmv2#trans...
python|machine-learning|computer-vision|huggingface-transformers
1
8,090
73,720,055
Replacing Square Brackets without value in .json array/pandas dataframe
<p>I was wondering if there is a way to remove/replace null/empty square brackets in json or pandas dataframe. I have tried to replace them after converting into string via .astype(str) and it is successful and/but it seems it converts all json values into string and I can not process further with the same structure. I...
<p>With the following toy dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({&quot;col1&quot;: [&quot;a&quot;, [1, 2, 3], [], &quot;d&quot;], &quot;col2&quot;: [&quot;e&quot;, [], &quot;f&quot;, &quot;g&quot;]}) print(df) # Output </code></pre> <p><a href="https://i....
json|pandas|dataframe|brackets
0
8,091
73,780,514
I am trying to define the following vector function, but keep getting an error
<p>Where am I going wrong? The function:</p> <p><a href="https://i.stack.imgur.com/wNmtb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wNmtb.jpg" alt="enter image description here" /></a></p> <p>The code I have written is as follows! Note the second def function is an attempt to integrate it using ...
<p>From the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html" rel="nofollow noreferrer">documentation</a>, <code>fun</code> should take <code>t</code> and <code>y</code> as it's first two arguments. Thus, you need to define <code>fun</code> as follows:</p> <pre><code>fun(t, y...
python|numpy|function|vector|ode
2
8,092
71,225,828
Python multiple separate pivot tables based on another column to separate excel files
<p>I am trying to produce multiple separate pivot tables for each distinct value in a different column in my df (like a different pivot table filtered by each). In the actual file there are several hundred R1's so was trying to find a way to loop over this somehow to produce them separately.</p> <p>If possible is there...
<p>While there may be prettier ways in dealing with the dataframes prior to writing to the sheets, this provided me the results you were looking for. It should scale with any number of 'R1''s as &quot;unique()&quot; provides a list of the unique names within R1. Then breaks it down for the variables you need and writes...
python|loops|pivot|pandas.excelwriter
1
8,093
71,442,051
How to identify and remove outliers from a dataframe that contains both numerical and catagorical values?
<p>I have a dataset and need to remove the outliers 3 standard deviations away from the mean for each numerical column. The rows which contain the outliers should then be dropped.</p>
<p>Here is an example of code that will do what your question asks:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( [ 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105 ] * 10 + [ 1, 11, 21, 31, 41, 161, 171, 181, 191, 201 ] ) print(len(df[0])) print(df.std()[0]) print(df[0].mea...
python|python-3.x|pandas|dataframe
1
8,094
52,241,792
Only convert string representation of number to number in Pandas
<p>I have a pandas <code>Dataframe</code> and I realize when my <code>Dataframe</code> columns only have string representation of numbers then the conversion will take place, otherwise it will not. The code below I am using to convert all numbers that are in string form to numbers.</p> <pre><code>import pandas as pd f...
<p>As <a href="https://stackoverflow.com/questions/52241792/only-convert-string-representation-of-number-to-number-in-pandas#comment91432115_52241792">@MadPhysicist</a> states, Pandas.Series have a single <code>dtype</code>. However, that <code>dtype</code> can be <code>object</code> which means anything goes. You'll...
python|pandas|dataframe
3
8,095
52,151,673
Dependencies missing in current linux-64 channels when trying to install tensorflow-gpu with conda command
<p>Hi I tried conda install tensorflow-gpu in my terminal and I get this</p> <pre><code>Error: Dependencies missing in current linux-64 channels: - tensorflow -&gt; numpy &gt;=1.11 -&gt; blas * mkl - tensorflow -&gt; numpy 1.11* -&gt; blas * openblas - tensorflow -&gt; tensorflow-tensorboard -&gt; numpy &gt;=1.11 ...
<p>As @pic0 has suggested, after doing</p> <p><code>conda update conda</code></p> <p>I were able to install all needed packages.</p> <p>If you have installed Anaconda on the default folder (for me is <code>/home/user/anaconda</code>), you should not need to use <code>sudo</code>.</p>
python|tensorflow
13
8,096
52,126,936
Python - Read an image from URL to resize and convert image to grayscale
<p>I want to read an image from URL to resize and convert it to grayscale. I have seen a number of examples from stackoverflow and I tried them out. However, it never successfully converts image to grayscale in my case. I'm not sure what went wrong here. This are what I tried. </p> <pre><code>import matplotlib.pyplot ...
<p>Give this code a try:</p> <pre><code>from skimage.io import imread, imshow from skimage.transform import resize from skimage.util import img_as_ubyte url = "https://prasadpamidi.github.io/images/image2.jpg" img1 = imread(url, as_gray=True) img2 = resize(img1, (32, 32)) img3 = img_as_ubyte(img2) imshow(img3) </code...
python-3.x|numpy|matplotlib|scikit-image
2
8,097
60,560,752
Tensorflow Square function recognition
<p>I am trying to learn the basics of machine learning. I am trying to train the AI the square function: 2^x</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow import keras model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squa...
<p>When you are training a <strong>Neural Network</strong>, which seems to be easy for you might be hard for the Computer. In your case training <strong>2 raised to nth power</strong>; training this pattern is somewhat hard to be discovered as the values changes <strong>drastically</strong>, this may or may not result ...
python|tensorflow|neural-network
0
8,098
60,739,867
i want to remove sqaure brackets from python list output
<pre><code> df = pd.read_excel('Websites.xlsx', usecols=[3]) webs = df.dropna() weblist = webs.values.tolist() for count in range(0,len(weblist)): print (weblist[count]) </code></pre> <p>the output is</p> <pre><code>['TRIPADVISOR.COM'] ['CHASE.COM'] ['WEBMD.COM'] ['WEATHER.COM'] ['INDEED.COM'] ['HOMEDEPOT.COM...
<p>I think output is one column <code>Dataframe</code>, so add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.squeeze.html" rel="nofollow noreferrer"><code>DataFrame.squeeze</code></a> for Series, last loop and change <code>url</code> with <code>f-strings</code>:</p> <pre><code>for...
python|pandas|list
2
8,099
60,750,288
Invalid device id when using pytorch dataparallel!
<h1>Environment:</h1> <ul> <li>Win10 </li> <li>Pytorch 1.3.0 </li> <li>python3.7</li> </ul> <h1>Problem:</h1> <p>I am using <code>dataparallel</code> in Pytorch to use the two 2080Ti GPUs. Code are like below:</p> <pre class="lang-py prettyprint-override"><code>device = torch.device("cuda" if torch.cuda.is_availa...
<p>Basically as pointed out by @ToughMind, we need specify</p> <pre><code>os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;0, 1&quot; </code></pre> <p>It depends though on the CUDA devices available in one's unit, so if someone has one GPU it may be appropriate to put, for example,</p> <pre><code>os.environ[&quot;C...
python-3.x|deep-learning|pytorch
3