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
369,200
41,388,235
What do I put in the "compute capability list" field when configuring Tensorflow?
<p>I'm building Tensorflow from source, and it asks me to </p> <pre><code>Please specify a list of comma-separated Cuda compute capabilities you want to build with. You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus. Please note that each additional compute capability signifi...
<p>Summarizing the comments as an answer:</p> <p>You can put 5.0 there, which is the compute capability that your card supports and should be your best choice. 3.5 is too low (doesn't use the full features of your card) and 5.2 is too high (not supported by your card); in either case, I believe the binary code would b...
build|configuration|tensorflow
3
369,201
27,615,838
What does the savethread / restore thread do?
<p>This is a follow up from this question:</p> <p><a href="https://stackoverflow.com/questions/27510838/when-does-a-numba-function-compile">When does a numba function compile?</a></p> <p>I am confused as to what this part of the code does:</p> <pre><code>from ctypes import pythonapi, c_void_p savethread = pythonapi....
<p>That code is used for calling a C function, in this case the functions are <code>PyEval_SaveThread</code> and <code>PyEval_RestoreThread</code>.</p> <p><code>savethread = pythonapi.PyEval_SaveThread</code> keeps a reference to the function <code>pythonapi.PyEval_SaveThread</code> in the variable <code>savethread</c...
python|multithreading|numpy|numba
2
369,202
27,825,461
Formatting JSON from a Pandas data frame for Highcharts within a Django template
<p>I have a Pandas data frame that I have converted to JSON like so:</p> <pre><code>json_data = data_df.to_json() </code></pre> <p>The original data frame looks like something similar to this:</p> <pre><code> col1 col2 col3 col4 0 1 2 2 -1 1 2 4 3 -2 2 3 6 4 -3 3 4...
<p>Try</p> <pre><code>var myData = {{ json_data | safe }}; </code></pre> <p><strong>UPDATE</strong>:</p> <p>Your data should be in format:</p> <pre><code>json_data = [ { 'name': "col1", 'data': [1, 2, 3, 4, 5]}, { 'name': "col2", 'data': [2, 4, 6, 8, 10]}, ] </code></pre> <p...
python|json|django|pandas|highcharts
3
369,203
27,806,577
Tricky Python array sorting
<p>Currently, I'm loading in some data into memory of the form:</p> <pre><code>5.579158e-19 0 0 5.678307e-19 1 0 ... 6.041513e-19 27 0 5.938317e-19 28 0 ... 5.978803e-19 38 1 5.590008e-19 39 1 5.588807e-19 0 2 5.670948e-19 1 2 ... </code></pre> <p>and so on with the command:</p> ...
<p>This can be done with no explicit loops. I'll use a smaller data set, and create a 10x10 array <code>mat</code>. If an index (i,j) is not in the CSV file, <code>mat[i,j]</code> will be 0.</p> <p>Here's the input file:</p> <pre><code>In [27]: !cat data.csv 0.1 0 0 0.2 1 0 0.3 7 0 0.4 8 0 0.5 ...
python|arrays|sorting|numpy
4
369,204
27,757,732
Find uncertainty from polyfit
<p>I use simple <code>polyfit</code> of order 2 to fit a line in sample data:</p> <pre><code>np.polyfit(x, y, 2) </code></pre> <p>which returns the coefficients.</p> <p>Now I want to find uncertainty of the fitted line, and tried to use <code>cov</code> argument, which returns 3x3 covariance matrix:</p> <pre><code>...
<p>This problem is addressed by <a href="http://ipnpr.jpl.nasa.gov/progress_report/42-122/122E.pdf" rel="noreferrer">"Estimating Errors in Least-Squares Fitting"</a> by P.H. Richter, 1995, TDA Progress Report 42-122.</p> <p>From the report, this paragraph may already be sufficient to you</p> <blockquote> <p>The fir...
python|numpy
12
369,205
27,787,930
How to get number of groups in a groupby object in pandas?
<p>This would be useful so I know how many unique groups I have to perform calculations on. Thank you.</p> <p>Suppose groupby object is called <code>dfgroup</code>. </p>
<h1>[pandas >= 0.23] Simple, Fast, and Pandaic: <code>ngroups</code></h1> <p>Newer versions of the groupby API provide this (undocumented) attribute which stores the number of groups in a GroupBy object.</p> <pre><code># setup df = pd.DataFrame({'A': list('aabbcccd')}) dfg = df.groupby('A') </code></pre> <p></p> <p...
python|pandas|dataframe|group-by|pandas-groupby
96
369,206
27,769,014
Python function to expand image (NumPy array)
<p>Say I have a greyscale image that is <code>3x3</code> and is represented by the <code>numpy</code> array below.</p> <p>I want to increase the size and resolution of the image, similar to a resizing function in a normal picture editing software, but I don't want it to change any of the values of the pixels, just to ...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>np.repeat</code></a> along both axes of the 3x3 <code>img</code> array:</p> <pre><code>&gt;&gt;&gt; img.repeat(2, axis=0).repeat(2, axis=1) array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ...
python|arrays|numpy|image-processing
6
369,207
27,517,805
Matrix with results of function f(x,y) in Python/numpy/pandas
<p>I have two series X and Y a function f(x,y) in Python. I would like to generate a matrix which contains the output of the function for every combination of X and Y. For instance, if the function was just a simple multiplication, it would look like this:</p> <pre><code> 1 2 3 4 5 ------------------- 1...
<p>The idiom is this: write function f(x,y) so that it can operate elementwise on Numpy arrays. For example, if you want to calculate <code>f(x,y) = x**2 + y**2</code>, this is</p> <pre><code>def f(x, y): return x**2 + y**2 </code></pre> <p>since power and sum operate elementwise so the expression is OK as it is....
python|numpy|matrix|pandas
1
369,208
27,842,229
Problems with numpy divide
<p>I am trying to use numpy divide to perform division on arrays and I have two arrays and I call it as follows:</p> <pre><code>log_norm_images = np.divide(diff_images, b_0) </code></pre> <p>I get the error:</p> <pre><code>operands could not be broadcast together with shapes (96,96,55,64) (96,96,55). </code></pre> ...
<p>You are attempting to broadcast a 4-D array together with a 3-D array. Based on NumPy's broadcasting behavior, this will only succeed if for each corresponding dimension, the dimensions are either equal or one of them is 1. Here's why it mismatches:</p> <pre><code>Your 4-D array: 96 x 96 x 55 x 64 Your 3-D array...
python|arrays|numpy
4
369,209
61,463,002
Product of two string arrays
<p>I have an array :</p> <pre><code>a1=['a','b','c'] </code></pre> <p>and another :</p> <pre><code>a2=['d','e','f'] </code></pre> <p>How do I create a DataFrame containing all elements in a2 for each element in a1 in Python?</p> <p>Expected output:</p> <pre><code>a d a e a f b d b e b f c d c e c f </code></pre>
<p>You can use <code>product</code> from <code>itertools</code></p> <pre><code>In [1]: from itertools import product In [2]: a1=['a','b','c'] In [3]: a2=['d','e','f'] In [4]: list(product(a1, a2)) Out[4]: [('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'd'), ('c', 'e'), ('c', ...
python|pandas|numpy
3
369,210
61,310,371
Visual Studio getting confused about Python versions
<p>I am calling a simple Python script from a C# file as</p> <pre><code> //ADD results and errors e.g., code Run GP tool.sln #region Running Python scripts Commented ProcessStartInfo psi = new ProcessStartInfo(); //Script variables, paths etc. psi.FileName = @"C:\Users\oguz\AppD...
<p>I removed the other Python versions and kept the one I need then it worked fine. I think those Python versions came with Visual Studio. That was the only way I was able to work it out. Hopefully, someone will give better answer. </p>
python|visual-studio|numpy|environment-variables
0
369,211
61,603,747
Whitespaces after addition to numpy array
<p>Why when I'm executing code below I get those weird whitespaces in output?</p> <pre><code>import numpy as np str = 'a a b c a a d a g a' string_array = np.array(str.split(" ")) char_indices = np.where(string_array == 'a') array = char_indices[0] print(array) array += 2 print(array) </code></pre> <p>output:</p> <...
<p>That's just numpy's way of displaying data to make it appear aligned and more readable.</p> <p>The alignment between your two lists changes</p> <pre><code>[0 1 4 5 7 9] [ 2 3 6 7 9 11] </code></pre> <p>because there is a two-digit element in the second list.</p> <p>In vectors it is more difficult to apprecia...
python|numpy
2
369,212
61,242,211
tensor flow lite multiple camera compatibility
<p>I would like to know if tensor flow lite on the raspberry pi 4 i could'nt find any information on the tensor flow website is compatible with multiples cameras for finding my cat in my house with multiple cameras</p>
<p>The challenge here is not in TensorFlow but in the interfacing the cameras. You can run inference with a batch size of 2, or 4, or however many cameras you have in your house to always keep an eye on your kitty </p>
tensorflow-lite
0
369,213
61,593,321
If both values in two different columns are NaN then 0 else 1
<p>My dataframe looks lie this:</p> <p>ts self_top_ask_price self_top_bid_price 0 2020-05-03 11:59:48.627436 NaN 0.08331 1 2020-05-03 11:59:36.286763 0.08367 0.08331 2 2020-05-03 11:59:24.279036 0.08367 NaN 3 2020-05-03 11:59:12.298755 NaN NaN</p> <p>What I am trying to achieve is that if both columns a...
<p>Check both columns if not missing values with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFrame.any</code></a> and then convert to numbers <code>0,1</code> mapping boolean by <a href="http://pandas.pydata.org/pandas-docs/stable/ref...
python|pandas
2
369,214
61,413,442
Docker Error When Compiling Tensorflow from source on Raspberry Pi
<p>I am attempting to build tensorflow from source on Raspberry PI using docker following this tutorial: <a href="https://www.tensorflow.org/install/source_rpi" rel="nofollow noreferrer">https://www.tensorflow.org/install/source_rpi</a> </p> <p>I have python 3.4 and 3.7 installed, and Docker version 18.06.3-ce. I get ...
<h2>Issue</h2> <p>The guide you are following references <em>cross-compiling</em>, which means they are building on a host machine, while you are trying to build on the Pi.</p> <p>To build Tensorflow go on raspberry pi you have to have <strong>libtensorflow.so</strong>, which is clibrary for Tensorflow used by GoLang...
python|python-3.x|docker|tensorflow|raspberry-pi
1
369,215
61,285,064
How to add an entry for all next dates once it first appeared
<p>I have a database that updates on a daily basis. Currently, it only has "active cases" - let's say when the value is 1 or higher. </p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ "Date": [ "2020-04-09", "2020-04-09", "2020-04-10", "2020-04-10", "2020-04-10", "2020...
<p>Idea is reshape by <code>pivot</code> and then replace missing values to <code>0</code> but only for rows if exist at least one non missing value before:</p> <pre><code>df1 = df.pivot('Date','ID','Value') df2 = (df1.mask(df1.ffill().notna() &amp; df1.isna(), 0) .stack() .astype(int) .r...
python|pandas
2
369,216
61,335,078
Colab throws errors when attempting to apply a SeparableConv2D layer in Tensorflow 2.0
<p>While learning Tensorflow 2.0 and experimenting with various structures I came across SeparableConv2D. I attempted to re-create a simple stack of VGG blocks that used the separable layers instead of standard convolutional layers, but Colab throws an error every time I attempt to add additional separable convolutio...
<p>You are missing a bracket :</p> <pre><code>model.add(layers.SeparableConv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)) </code></pre> <p>should be</p> <pre><code>model.add(layers.SeparableConv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)) ) </code></pre> <p>Note the <code>)</code> at the ...
deep-learning|tensorflow2.0|convolution|tf.keras
0
369,217
61,253,542
Add a new row to a CSV Dataframe inside a for loop with Pandas
<p>Hello I am really stuck and cannot get my head around this problem really appreciate any help or guidance. I have tried to ask this question a couple of times different ways but have had no full success on completing my task.</p> <p>I am attempting to take a cell from each row in spreadsheet"a.csv" and then use tha...
<p>A possible way is to add the new row at the end of the dataframe and store the IDNumber in it. At the end of the loops, you can sort the dataframe on IDNumber and set it to blank on lines having no Title. Here is a possible code:</p> <pre><code>for index, row in df1.iterrows(): for i, r in df2.iterrows(): ...
python|pandas|csv|dataframe
1
369,218
61,516,480
Grab last file from folder Python
<p>This is an entire edit since I found what my issue is, but I am still not able to fix this issue.</p> <p>I am trying to build a function that grabs the last file from a folder based on user input and turn it into a data frame. I have multiple folders assigned as constants. The questions I find are looking for the l...
<p><code>sort_values</code> works with DataFrame, you are using it with Series (this is the reason of the error: <code>sort_values() got an unexpected keyword argument 'by'</code>)</p> <p>I suggest you modify inside <code>top_cases</code> function:</p> <pre><code> if series == 'Country': df = daily_framer(...
python|pandas|matplotlib
0
369,219
61,264,212
"undefined input shape at index" warning in training
<p>Tensorflow2 is used in training and I have quite a number of warnings printed out in object classification training. What could be the reason for those warnings?</p> <pre><code>2020-04-17 12:15:16.091784: W tensorflow/core/common_runtime/shape_refiner.cc:88] Function instantiation has undefined input shape at index...
<p>I had similar errors popping up. I used a dataset from a generator without specifing the output shape of the generator. After adding the output shape, no warning was generated:</p> <pre><code>tf.data.Dataset.from_generator(generator, output_types=(tf.float32, tf.float32), output_shapes=(tf.TensorShape([2997, 16]), t...
tensorflow2.0
0
369,220
61,181,237
Tensorflow: FailedPreconditionError: Error while reading resource variable from Container: localhost. When running sess.run() on custom loss function
<p>I have a code running Keras with TensorFlow 1. The code modifies the loss function in order to do deep reinforcement learning:</p> <pre><code>import os import gym import numpy as np import pandas as pd import matplotlib.pyplot as plt env = gym.make("CartPole-v0").env env.reset() n_actions = env.action_space.n state...
<p>The initialization operation should be fetched and run (only one time) <strong>after</strong> the variables (i.e. model) have been created or the computation graph has been defined. Therefore, they should be put right before running the training step:</p> <pre><code># Define and create the computation graph/model #...
tensorflow|machine-learning|keras|deep-learning|tf.keras
6
369,221
61,334,586
How to export a DataFrame to multiple sheets of Excel File
<p>Assume that I have a dataframe of 8000 rows x 7 columns.</p> <p>Overview of the data</p> <pre><code>data = pd.read_excel('tmp.xlsx') data.head(10) </code></pre> <pre><code>ID Type CatID Val1 val2 Comment Disposition 20192658 N 52 256 358 Processing In Progress 201...
<h2>Given your dataframe <code>data</code>:</h2> <ul> <li>Iterates through each unique ID and slices the dataframe for those values, and then saves to the file.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd with pd.ExcelWriter('data.xlsx') as writer: for i, value in enumerate(dat...
python|excel|pandas|dataframe
2
369,222
61,488,097
How to groupby a column every time its sum reaches a specified amount?
<p>I have a data frame <code>df</code> like this</p> <pre><code> x 0 8.86 1 1.12 2 0.56 3 5.99 4 3.08 5 4.15 </code></pre> <p>I need to perform some sort of <code>groupby</code> operation on <code>x</code> to aggregate <code>x</code> every time its sum reaches 10. If the index of <code>df</code>...
<p>Here's one approach:</p> <pre><code># cumulative sum and modulo 10 s = df.x.cumsum().mod(10) # if value lower than 10, we've reached the value m = s.diff().lt(0) # groupby de cumsum df.x.groupby(m.cumsum().shift(fill_value=0)).sum() x 0 10.54 1 13.22 Name: x, dtype: float64 </code></pre>
python|pandas|pandas-groupby
2
369,223
61,331,898
Tensorflow tflite c++ api inference for matrix data array
<p>I am creating a class that will be used to run inference on an embedded device (not raspberry pi) in c++ using tensorflow's tflite c++ api. Tensorflow doesn't seem to have decent documentation on how to run inference for n number of samples of image data. My data shape in python is (n, 5, 40, 1) [n samples, 5 heig...
<p>From the Tensorflow documentation we can find below details,</p> <blockquote> <p>It should be noted that:</p> <ul> <li>Tensors are represented by integers, in order to avoid string comparisons (and any fixed dependency on string libraries).</li> <li>An interpreter must not be accessed from concurrent thr...
c++|tensorflow|tensorflow-lite
-1
369,224
61,561,537
Encoding, Decoding Pinyin Characters in Python 3.7
<p>I'm having trouble en-/decoding Pinyin characters from an excel file.</p> <p>The structure of that file looks like this:</p> <p><a href="https://i.stack.imgur.com/NAVA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NAVA0.png" alt="enter image description here"></a></p> <p>[...]</p> <p>and I ...
<p>Finally figured out the problem. I was running it through VS 'Code Runner' extension which caused the error. I guess it is possible to configure it somehow to make it work, but for the moment I just use standard terminal within VS Code or run it directly through CLI.</p>
python-3.x|pandas|encoding|utf-8|decoding
0
369,225
61,425,578
How to reshape or transpose a dataset by considering selected columns and rows in a large dataset (World Bank example)
<p>I am trying to wrangle a dataset from the World Bank website and I need to reshape in a way for the series name to be the first row and the years to be all structured along a column. There are 50 years and over 100 indicators in the dataset so this reshape needs some form of automatisation to work for me. An extract...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFr...
python|pandas|reshape|transpose|data-wrangling
1
369,226
61,248,942
what does the numpy vander function do and why use it in a regression?
<p>I am trying to under the code written in this <a href="https://searchcode.com/codesearch/view/88477497/" rel="nofollow noreferrer">module</a> to understand cointegration.</p> <p>However when I step through the code I am confused by the last line in the section of code below. I have read the documentation of the van...
<p>The function np.vander returns an array where the first column is x^(N-1), the second x^(N-2) and so forth. Look this example:</p> <pre><code>x = np.array([1, 2, 3, 5]) N = 3 np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) </code></pre> <p>In your code N= order+1 and X=np...
python-3.x|numpy|regression
1
369,227
61,521,464
pytorch F.cross_entropy does not apply gradient to weights
<p>I'm trying to train an MLP from scratch using <code>torch</code> tensors and some of the built-in loss functions. I have IRIS-data downloaded and stored in tensor <code>(100, 4)</code> and labels <code>(100)</code> (integers 0-2) in <code>data_tr</code> and <code>targets_tr</code>. I have enabled gradients on the i...
<p>If you want to update the weights without using an optimizer, you have to either use <code>torch.no_grad()</code> or update their <code>data</code> directly to ensure autograd is not tracking the update operations. </p> <pre class="lang-py prettyprint-override"><code>with torch.no_grad(): W1 -= lr * W1.grad ...
pytorch|gradient
0
369,228
61,549,822
Extracting all Nouns from a CSV File Using NLTK
<p>I am new to both Python and NLTK. I would like to ask how can I extract all nouns from a list of sentences in CSV file using nltk? </p> <p>the list of sentences is in CSV file and is in this form of: </p> <pre><code> **Sentences** </code></pre> <p>1 I like to eat bread<br> 2 I am excited to watch this ...
<p>Well, you can use pandas to change the CSV file to the DataFrame.(<code>pd.read_csv('filename')</code>) Next thing is you have to play with NLTK. Here is the link to the <a href="https://www.nltk.org/book/ch07.html" rel="nofollow noreferrer">NLTK</a>.</p>
python-3.x|pandas|nltk
0
369,229
61,603,619
LSTM Keras sorting out the X and y input dimensions
<p>I am trying to build an LSTM and am confused about the best way to shape my data.</p> <p>I have a dataframe that looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-overr...
<p>if MULTIPLE timesteps are required you have to create a sliding window function which helps you to reshape your data, for this purpose <code>TimeSeriesGenerator</code> from Keras is a good instrument (<a href="https://machinelearningmastery.com/how-to-use-the-timeseriesgenerator-for-time-series-forecasting-in-keras/...
python|tensorflow|keras|deep-learning|lstm
1
369,230
61,470,832
pickle.load cannot open up a (Stylegan2 network) pickle model on my local machine, but can on the cloud
<p>Stylegan2 uses network pickle files to store ML models. I transfer trained one model, which I am able to open up on cloud servers. I have been generating images from this model fine with the following setup: </p> <ul> <li>Google Colab: Python 3.6.9, CUDA 10.1, tensorflow-gpu 1.15, CuDNN 7.6.5</li> </ul> <p>However...
<p>Actually, I figured it out by printing out what version was throwing the error. The version printed was '4'. I realized that this matched the pickle (HIGHEST_PROTOCOL) and that what I needed was the newest pull of the Stylegan2 repository, which included pickle format_version 4 in their allowed versions.</p>
tensorflow|machine-learning|pickle|google-colaboratory
0
369,231
61,353,010
Problem importing (and installing) NumPy in Jupyter Notebook
<p>I am having major trouble right now trying to use numpy in my jupyter notebook.</p> <p>When I first tried to simply <strong>"import numpy"</strong>, it came back with the error: <strong>"ModuleNotFoundError: No module named 'numpy'"</strong></p> <p>I then read somewhere that I probably needed to install numpy. </p...
<p>In my case, inside Jupyter notebook, you need to change Kernel (Anaconda environment). I thought you changed environment using <code>conda activate myEnv</code>, but when launching Jupyter, it defaults to the root environment. I hope this is in fact true- I am a noob in Anaconda.</p>
python|numpy|jupyter-notebook
0
369,232
61,219,125
pandas dealing with a column with multiple values separated with delimiter for data analysis
<p>here's a python self learner trying to find a way working with columns with multiple values. the dataset is TMDb Movie Dataset and there are multiple values columns are like genres, cast etc.</p> <p>I managed splitting values and counting them, it's okay. but what if I want to see the relationship between genres an...
<p>I would use something like the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer">stack</a> function to create a row for every item when splitting. For example, when you want to group by genre, create a row for genre when splitting (keeping othe...
pandas
0
369,233
61,401,064
operations on arrays in python from memory perspective
<p>I am trying to understand the memory allocation in the following operation:</p> <pre><code>x_batch,images_path,ImageValidStatus = tf_resize_images(path_list, img_type=col_mode, im_size=IMAGE_SIZE) x_batch=x_batch/255; x_batch = 1.0-x_batch x_batch = x_batch.reshape(x_batch.shape[0],IMAGE_SIZE[0]*IMAGE_SIZE[1]*IMA...
<p>I see "tf" in your code, so I am unsure if you are asking about tensors or arrays. Lets assume you are asking about arrays. In general, arrays are written to memory once and then manipulated. For example, </p> <pre><code>import numpy as np data = np.empty((1000,30,30,5)) #This took up 1000*30*30*5*dtype_size bytes...
python|numpy|numpy-ndarray
0
369,234
61,308,861
Add values in column based on condition in Python
<pre><code>Source_No Parent Type Amt 123 123 Tail 100 456 123 Coll 100 789 123 Coll 100 </code></pre> <p>I want the code to create a new column a new column 'Tot_Amt' which will add the Amt of all Source_No, where Parent = Source_No and for other </p> <p>Expected out...
<p>Here you go:</p> <pre><code>df["Tot_Amt"] = (df.groupby(["Parent"])["Amt"].sum() - df.groupby(["Source_No"])["Amt"].sum()).fillna(0).reset_index(drop=True) </code></pre>
python|pandas
1
369,235
61,395,585
How to go through a pandas data frame and only keep rows that have the same value throughout the entire row?
<p>If I have a pandas data frame like this:</p> <pre><code> NaN NaN NaN 2 2 2 NaN NaN NaN 2 7 9 1 NaN NaN 2 6 4 8 NaN NaN 7 6 9 1 NaN NaN 1 1 1 NaN NaN NaN 2 7 9 2 NaN NaN 2 2 2 8 NaN NaN 7 6 9 1 NaN NaN 1 NaN 1 </code></pre> <p>How do I only keep rows wh...
<p><code>DataFrame.nunique</code> will not count <code>NaN</code> so it suffices to check if there is a single unique value row-wise</p> <pre><code>df.loc[df.nunique(axis=1).eq(1)] 0 1 2 3 4 5 0 NaN NaN NaN 2 2.0 2 4 1.0 NaN NaN 1 1.0 1 6 2.0 NaN NaN 2 2.0 2 8 1.0 NaN NaN 1 NaN 1 </code>...
python|python-3.x|pandas
2
369,236
61,473,330
CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`
<p>I got the following error when I ran my pytorch deep learning model in colab</p> <pre><code>/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1370 ret = torch.addmm(bias, input, weight.t()) 1371 else: -&gt; 1372 output = input.matmul(weight.t()) ...
<p>This error can actually be due to different reasons. It is recommended to debug CUDA errors by running the code on the CPU, if possible. If that’s not possible, try to execute the script via:</p> <pre><code>CUDA_LAUNCH_BLOCKING=1 python [YOUR_PROGRAM] </code></pre> <p>This will help you get the right line of code wh...
nlp|pytorch|bert-language-model
20
369,237
61,343,278
Runtime warning when importing libraries in jupyter notebook
<p>So, I have never had this issue before on prior laptops- but recently on my new laptop- I get runtime warnings when trying to import libraries into Jupyter notebook- I'm not sure of the cause or how to fix it. Any solutions? </p> <p><a href="https://i.stack.imgur.com/2qWJd.png" rel="nofollow noreferrer">enter image...
<p>Maybe there is some problem with the package which showing warning. Try to re-install the package. </p> <p>First check whether the package working properly. If not install the pakage. Here in your screenshot it shows problem with numpy. To install numpy follow</p> <pre><code>pip install numpy </code></pre> <p>Or<...
python|pandas|numpy|scipy|jupyter-notebook
0
369,238
61,584,678
how to reverse a dataframe to its original form in pandas
<p>i have data frame and used the command <code>pd.pivot_table(df,columns="category",index=["year","period"])</code> did some data processing at this dataframe and i want to reverse the process to get the original formation of the df. i tried with <code>pd.melt</code> and <code>pd.wide_to_long</code> without any luck. ...
<p>In general, for a given way to construct a pivot table from a data frame, two different data frames may yield the same pivot table. So this process is irreversible. For example, compare the following to your <code>df</code> and <code>table</code>:</p> <pre class="lang-py prettyprint-override"><code>data2 = {"col1":...
python|pandas|dataframe|pivot|melt
0
369,239
61,566,993
Pip installs files to the old version of Python (Pip, Pandas, Python, Mac)
<p>I just started learning about Python (on macOS Mojave). I downloaded the latest version of Python and wanted to download software libraries like pandas.</p> <p>So firstly I downloaded pip like that: sudo easy_install pip</p> <p>Then I installed pandas using pip, however pandas location is: Requirement already sati...
<p>You might have both <code>pip</code> and <code>pip3</code> installed, where the first is used for python <code>2.7</code> and the second for python <code>3.8.2</code></p> <pre><code>pip3 install pandas </code></pre>
python|pandas|macos|pip
2
369,240
61,488,796
datetime is chaning date and month wrongly for some cases
<p>I am trying to change a <code>object</code> to a <code>datetime</code> value.</p> <pre><code> id date 1 07/03/2020 2 20/02/2020 </code></pre> <p>In the above <code>df</code> the column <code>date</code> is in the format <code>%d%m%Y</code> in strings value and when I apply <code>df['date'] = pd.dateti...
<p>You should try specifying the format when you convert:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y') </code></pre>
python|pandas|datetime
2
369,241
61,220,657
How to strip all text located to the left of the first number Python
<p>I am trying to augment addresses. An example string:</p> <pre><code>"Unit 3/45 main st, London" </code></pre> <p>Alternatively, I am trying to create addresses from dirty inputs by a customer, eg</p> <pre><code>"U 68 25 MARKET ST" "52/225 Jamboree Ave Old Saints Retirement Village" "Unit 9 13-15 Endeavour Str...
<p>In response to how to strip all text to the left of the first number using python:</p> <pre><code>samp_string = &quot;U 68 25 Market St&quot; numbers = ['0','1','2','3','4','5','6','7','8','9'] def strip_left(string): length = len(string) count = 0 for i in range(0,length): if (count == 0) and s...
python|string|pandas
0
369,242
61,425,961
How to generate predictions based on the distribution of the data using Python
<p>My dataframe currently looks like this (lets call this df_1).</p> <pre><code>date var1 1-1-01 0.1 2-1-01 0.02 3-1-01 3.00 4-1-01 4.5 5-1-01 0.9 6-1-01 0.22 </code></pre> <p>The <code>var_1</code> is normally distributed. (see photo below) <a href="https://i.stack.imgur.com/NUfGI.png" rel="nofol...
<p>You can fit a normal distribution to <code>var_1</code>, and then draw samples from it,</p> <pre class="lang-py prettyprint-override"><code>import scipy import numpy as np # fit to var_1 mu, std = scipy.stats.norm.fit(df['var_1']) # generate data for var_2 var_2 = np.random.normal(mu, std, size=len(df['var_1'])) ...
python|pandas|numpy|dataframe
1
369,243
61,571,771
pd.to_datetime format argument is rejected
<p>I can not understand this exception:</p> <pre><code>date = '01/01 24:00:00' pd.to_datetime(date, format = '%m/%d %H:%M:%S') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\Anaconda3\envs\tf2\lib\site-packages\...
<p><strong>Short answer</strong>: 24 is not a valid hour.</p> <p>The hours should be in the 0-23 range, as is specified in the <code>datetime</code> package for the <code>%H</code> format directive:</p> <pre><code>%H Hour (24-hour clock) as a zero-padded decimal number. <b>00, 01, …, 23</b></code></pre> <p>so <code>...
python-3.x|pandas|format|strftime|string-to-datetime
1
369,244
61,363,712
How to print a pandas.io.formats.style.Styler object
<p>I have the following code which produces a pandas.io.formats.style.Styler object:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'text': ['foo foo', 'bar bar'], 'number': [1, 2]}) df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) df...
<p>I found the answer for this:</p> <pre><code>import pandas as pd from IPython.display import display import numpy as np df = pd.DataFrame({'text': ['foo foo', 'bar bar'], 'number': [1, 2]}) df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) df2 = df1.set_prope...
python|pandas|dataframe|pandas-styles
12
369,245
61,440,184
Who is Scott? - ValueError in Seaborn pairplot: Could not convert string to float: 'scott'
<h2>Who is Scott?</h2> <h3>Problem</h3> <p>I get the following error when trying to add the Education attribute from the Loan Prediction dataset to a pairplot using seaborn:</p> <blockquote> <p>ValueError Traceback (most recent call last) ~/anaconda3/lib/python3.7/site-packages/sta...
<p><code>scott</code> is the name of a method to choose the bandwidth when plotting a Kernel Density estimation (KDE). It is named after DW Scott (1).</p> <p>I cannot look at your data, but my guess is that something is weird with one of the pairs of variable for a certain hue-level that prevents seaborn to calculate ...
python|pandas|matplotlib|runtime-error|valueerror
4
369,246
61,207,129
Less memory consumption for df.loc and drop rows which specific characters in a specific column
<p>i am loading a big dataframe in python, with several columns and million of rows, so for sure this is quite memory consuming. To exclude some types in a specific column I use:</p> <pre><code>import pandas as pd files = glob.glob("Path/*.csv") dfs = [pd.read_csv(f, sep='\t', encoding='unicode_escape') for f in files...
<p>You can deal with the memory issues using <code>dask</code></p> <pre><code>import dask.dataframe as dd df = dd.read_csv('file.csv') df = df.loc[~df.Type.isin(['A', 'B',...,'F'])] df = df.compute() # this will give back the pandas dataframe </code></pre> <p>This will silently carryout operations chunk-wise in the ...
python|pandas
1
369,247
61,525,611
I am trying to build a neural network with one neuron using the pytorch library. It keeps giving me an error
<p>I am trying to build a neural network with one neuron using the pytorch library. This is my code (the error is at the bottom)</p> <pre><code>import numpy as np import random import matplotlib.pyplot as plt x_train = np.array([random.randint(1,1000) for x in range(1000)], dtype = np.float32) y_train = np.array([int...
<p><code>torch</code> expects 2D input, so you need to add a new dimension to your inputs tensors.</p> <pre><code>X_train = torch.from_numpy(x_train[..., np.newaxis]) X_test = torch.from_numpy(x_test[..., np.newaxis]) </code></pre> <p>As someone commented above, you can also use <code>torch.unsqueeze</code>:</p> <pr...
python|numpy|deep-learning|neural-network|pytorch
0
369,248
61,232,835
pandas options: apply float format to floats in tuples
<p>I have a dataframe which looks as follows:</p> <pre><code>import pandas as pd df = pd.DataFrame({"A":[1.25,2.25], "B":[(3.25,4.23),(1.22,6.33)]}) A B 0 1.25 (3.25, 4.23) 1 2.25 (1.22, 6.33) </code></pre> <p>Now, I want all floats to have only one decimal when I print the dataframe. So I apply...
<p>It can't be done globally, but can be specified using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Finer-Control:-Display-Values" rel="nofollow noreferrer">styler</a> on a column level:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'A': [1.25, 2.25], 'B': [(3....
python|pandas
0
369,249
61,404,150
Searching data frame by indexes and exporting information
<p>So, I have indexes in <em>range</em> data frame. I want to use them to find values in test dataframe and extract values from into new data frame. My current code is:</p> <pre><code>d = [] for index in _range_.index: d.append((test.loc[[index],:])) </code></pre> <pre><code>_range_ data set: a 23...
<p>You could <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer">join</a> the two dataframes together on their common index using 'inner' then keep only the <strong>test</strong> columns. </p> <pre><code>cols = __test__.columns df = __range__.join(...
python|pandas|dataframe
0
369,250
61,588,450
Arrage dataframe based on the data presence in columns in multilevel dataframe
<p>I have a multilevel columns in the pandas <code>df</code> with the index as <code>appid</code> as follows:</p> <pre><code>year |2016 2017 2018 2019 2016 2017 2018 2019 |ttl ttl ttl ttl tta tta tta tta -----------------------------------------------------------------...
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> for years to columns, then use <code>justify</code>, filter last 3 columns, create DataFrame and reshape back by <a href="http://pandas.pydata.org/p...
python|pandas|sorting|multilevel-analysis
1
369,251
61,231,963
Convert DD-MMM-YY to YYYY/MM/DD in Pandas
<p>DoB column in my dataset has date in the format below:</p> <pre><code>0 12-Jan-79 1 13-Jan-70 2 11-Mar-84 3 11-Mar-84 4 01-May-86 ... 1080 15-Mar-81 1081 07-Jul-96 1082 11-Apr-90 1083 22-Oct-64 1084 12-Jul-95 </code></pre> <p>I need to convert the same int...
<p>You should specify the format:</p> <pre><code>df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth'], '%d/%m/%y') </code></pre>
python|pandas|date
0
369,252
61,607,740
How to resample 1 minute data to 10 minute data?
<pre><code>import pandas as pd file = pd.read_csv('D:\\Ayush\\Data\\Bank nifty Data\\Testing.csv') file['Date_time'] = file['Date/Time'] + ' ' + file['Time'] file['Date_time'] = pd.to_datetime(file['Date_time']) file.drop(columns=['Date/Time','Time'],inplace=True) file['Date'] = file['Date_time'].dt.date file['Date_t...
<pre><code>file.high.resample('10min').max() </code></pre> <p>I will suggest you to do the resample 1 by 1. </p> <p><a href="https://benalexkeen.com/resampling-time-series-data-with-pandas/" rel="nofollow noreferrer">https://benalexkeen.com/resampling-time-series-data-with-pandas/</a></p>
python|pandas|resampling
1
369,253
61,342,916
Groupby cumulative sum in pandas based on specific condition
<p>I have a data frame as shown below.</p> <pre><code>B_ID No_Show Session slot_num Patient_count 1 0.4 S1 1 1 2 0.3 S1 2 1 3 0.8 S1 3 1 4 0.3 S1 3 2 5 0.6 S1 4 1...
<p>So similar to your <a href="https://stackoverflow.com/q/61364013/9274732">question</a> later on, i think you need to create a function to return your two columns then <code>groupby.apply</code>. And if I understand correctly how you want to increment U_slot_num, then you can do:</p> <pre><code>def create_u_columns ...
pandas|pandas-groupby
1
369,254
68,545,690
Concatenate ragged inputs in Keras
<p>The following code creates a dummy model that concatenate 2 inputs. One input is used with an Embedding layer with output size of 5, while the second input is just merged with the output of the Embedding layer:</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.keras.layers import Input, Embed...
<p>Using <a href="https://www.tensorflow.org/api_docs/python/tf/concat" rel="nofollow noreferrer"><strong>tf.concat</strong></a> instead of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Concatenate" rel="nofollow noreferrer"><strong>tf.keras.layers.Concatenate</strong></a> resolves the issue, beca...
python|tensorflow|machine-learning|keras|ragged
1
369,255
68,603,456
Is there a way how i can find the index of an multidimensional numpy array by matching it to another numpy array?
<p>Lets say i have the following case:</p> <pre><code>array1=np.array([[1,0,0],[0,1,0],[0,0,1]]) array2=np.array([0,0,1]) </code></pre> <p>now</p> <pre><code>array1[2] </code></pre> <p>gives me the output</p> <pre><code>[0,0,1] </code></pre> <p>so now i want to have code that gives the index of <code>array1</code> (in...
<p>I am not sure I understand your question correctly. But you could either do this:</p> <pre><code>import numpy as np np.where((array2 == array1).all(axis=1)) </code></pre> <p>You can do this:</p> <pre><code>index = np.argmax([0,0,1]) </code></pre> <p>Or use this:</p> <pre><code>indices = np.where(np.array([0,0,1]) ==...
python|arrays|numpy|indexing
1
369,256
68,514,308
Filling up a new column with values based on 2 window dates in another dataframe (in Pandas and PySpark)
<p>I have 2 dataframes. df1 looks like this:</p> <pre><code>DATE QUANTITY 2015-10-28 14 2015-10-29 881 2015-10-30 533 2015-10-31 634 2015-11-01 637 </code></pre> <p>...</p> <p>I have a second df, df2 which is like this:</p> <pre><code>STARTDATE ENDDATE VALUE 2015-10-25 2015-10-29 2 2015-11-01 ...
<p><strong>Pandas</strong>:</p> <p>You can create a date range using <code>pd.to_datetime</code> and then explode followed by an outer merge:</p> <p>Starting with converting the date values to datetime dtype (ignore this step if already a datetime dtype)</p> <pre><code>df2[['STARTDATE','ENDDATE']] = df2[['STARTDATE','E...
python|pandas|dataframe|pyspark
1
369,257
68,621,184
Incrementally add pandas column value
<p>I have a dataframe like this:</p> <pre><code>id trade_id tradedate settledate amt 3136 6828 20200616 20200630 15000000.0 3136 6934 20200616 20200630 15000000.0 3136 7007 20200618 20200630 30000000.0 3136 7050 20200620 20200630 25000000.0 3137 7091 ...
<p>Use <code>groupby</code> to get sum by <code>id</code> and <code>tradedate</code> but first convert <code>tradedate</code> to a real date for upsampling:</p> <pre><code>df['tradedate'] = pd.to_datetime(df['tradedate'], format='%Y%m%d') </code></pre> <pre><code>&gt;&gt;&gt; df.groupby(['id', 'tradedate'])['amt'].sum(...
pandas|dataframe|python-3.6
2
369,258
68,621,021
when converting to csv from python i a missing first column in excel
<p>i had header info like</p> <pre><code>header = Sr. No.^Name of Deductor^TAN of Deductor^^^^^Total Amount Paid / Credited(Rs.)^Total Tax Deducted(Rs.)^Total TDS Deposited(Rs.)^Sr. No.^Section^Transaction Date^Status of Booking^Date of Booking^Remarks^Amount Paid / Credited(Rs.)^Tax Deducted(Rs.)^TDS Deposited(Rs.) </...
<p>The first column contains the index labels, which you can suppress like this:</p> <pre><code>dfs[&quot;PART A&quot;].to_csv(&quot;f.csv&quot;, index=False) </code></pre>
python|excel|pandas
0
369,259
68,501,033
Keras LSTM model overfitting
<p>I am using an LSTM model in Keras. During the fitting stage, I added the validation_data paramater. When I plot my training vs validation loss, it seems there are major overfitting issues. My validation loss just won't decrease.</p> <p>My full data is a sequence with shape <code>[50,]</code>. The first 20 records ar...
<p>20 records as training data is too small. There won't be enough variation in the training data for the model to approximate a function accurately, and so your validation data, which is likely much smaller than 20, will likely contain an example wildly different from just those 20 in the training data (i.e. it hasn't...
python|keras|time-series|lstm|tensorflow2.0
0
369,260
68,622,915
How to analyze data efficiently
<p>TLDR: I would like some suggestions on how I can improve my code.</p> <p>I'm learning data science from datacamp, I have an beginner-intermediate knowledge about coding. This is a data-analysis project I did today and am not happy with my code since it feels jumbled and inefficient.</p> <p>In the below code I'm supp...
<p>I suggest that you take a look at the docs, and read about <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferr...
python|pandas|dataframe
0
369,261
68,684,274
Pandas - conditional row average
<p>I have a dataframe:</p> <pre><code>x = pd.DataFrame({'1':[1,2,3,2,5,6,7,8,9], '2':[2,5,6,8,10,np.nan,6,np.nan,np.nan], '3':[10,10,10,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]}) </code></pre> <p>I am trying to generate an average of a row but only on values greater than 5. For instance - if a row had values of ...
<p>You can mask the values greater than 5 then take mean:</p> <pre><code>x.where(x&gt;5).mean(1) </code></pre> <p>Or:</p> <pre><code>x.mask(x&lt;=5).mean(1) </code></pre>
python|pandas|dataframe
3
369,262
68,485,434
Pandas systematically identify missing multi-index categorical values
<p>I have the following dataframe, in the ID column we can have 2 feedbacks, good or bad. I cannot figure out how to systematically identify if a user is missing a feedback and if it is missing, add a new line with the missing feedback in the level 1 and add 0 to all values.</p> <pre><code>import pandas as pd df = {'I...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>idx = pd.MultiIndex.from_product( [ df.index.get_level_values(0).unique(), df.index.get_level_values(1).unique(), ], names=[&quot;USERS&quot;, &quot;ID&quot;], ) df = df.reindex(idx, fill_value=0) print(df) </code></pre> <p>Prints:...
python|pandas|dataframe|categories
2
369,263
68,662,988
Convert JSON to CSV and print directly (Python)
<p>I need to convert a json object to csv and print it directly and NOT write it to a file like the pandas method does. Is there a way to do so?</p>
<p>If I understand correctly:</p> <p>you can try via <code>read_json()</code>+<code>to_csv()</code>:</p> <pre><code>print(pd.read_json('yourjson.json',lines=True).to_csv()) </code></pre> <p>OR</p> <p>If your json is stored in a variable then:</p> <pre><code>print(pd.Series(your json variable).to_csv()) </code></pre> <p...
python|json|pandas|csv
0
369,264
68,672,902
Parse pandas dataframe with column contain array
<p>I have data from csv file in pandas dataframe. One column contain array (I mean its JSON originally) who I need parse.</p> <p>Example of one row:</p> <pre><code>ID_access,ID_part,ID_user,DATE,DESCRIBE,NOTE 865434334,66784,5468,2020-12-18 09:56:00,&quot;Array ( [ar] =&gt; 0034 [ident_a] =&gt; Array ( ...
<p>You can use regexp, for example:</p> <pre><code>import re import pandas as pd rows = re.findall(r&quot;(\d+),(\d+),(\d+).([-:\s\d]+).*?\[id_sec] =&gt; ([^\n]+)\s+\[note] =&gt; ([^\n]+)\s+\[date] =&gt; ([^\n]+)&quot;, t, re.S) df = pd.DataFrame(rows, columns = ['ID_access','ID_part','ID_user','DATE','id_sec','note',...
json|python-3.x|pandas|dataframe
1
369,265
68,515,585
get column names using criteria and column value using pandas?
<p>I have a dataframe like as shown below</p> <pre><code>df = pd.DataFrame({'sub_id': [101,101,101,102,102,103,104], 'test_status':['Y','N','Yes','No','Not sure','NOT SURE','YES'], 'remarks':[np.nan,&quot;testvalue&quot;,np.nan,&quot;ilike&quot;,&quot;wild&quot;,np.nan,&quot;test&q...
<p>Use <code>isin</code> and keep only columns where all rows are True:</p> <pre><code>&gt;&gt;&gt; df.columns[df.isin(response).all()].tolist() ['test_status', 'reg_value'] </code></pre> <p>Modify <code>response</code> to be more elegant:</p> <pre><code>resp = fr&quot;({'|'.join(set([r.lower() for r in response]))}) <...
python|python-3.x|pandas|dataframe|series
4
369,266
68,644,644
Pandas: plot a dataframe with on its right side rectangle colored according to an array's values
<p>I have a dataframe with 100 rows and 4 columns. I have an array (size 100,1) filled with values spanning between 0 and 1. I would like to plot my dataframe, with on its right side a rectangle which will take a color depending on the value of the array at a specific row (see the poor drawing I made, the array is writ...
<p>My solution would be to use <code>plot.subplots</code> to create two plots with the <code>width_ratios</code> argument as something like 19:1. On the left hand side you plot the data frame as usual, on the right hand side you plot the vector. Notice that I am using <code>vmin</code> and <code>vmax</code> to set the ...
pandas|dataframe|matplotlib|plot|seaborn
1
369,267
68,651,332
ValueError: expected sequence of length 0 at dim 2 (got 1)
<p>I've recently started a tutorial about Neural Networks with Python. I am working on a cat/dog classification task with a CNN. However even though I thought I've done exactly what the tutorial told me to do, I somehow ended up with a dim error.</p> <p><a href="https://www.youtube.com/watch?v=1gQR24B3ISE&amp;list=PLQV...
<p>You didn't define the labels properly, it shouldn't be</p> <pre><code>np.eye(2, self.LABELS[label]) </code></pre> <p>but instead:</p> <pre><code>np.eye(2)[self.LABELS[label]] </code></pre>
python|neural-network|pytorch|conv-neural-network|valueerror
0
369,268
68,857,847
How to fix incorrect format in pandas column?
<p>I have a pandas dataframe called df1</p> <pre><code>ID| ACTIVITY | Date 1 | activity 1 | 2/04/2016 2 | activity 2 | 3/04/2015 3 | activity 3 | 7/05/2016 3 | activity 4 | 2/04/2016 4 | activity 3 | 2/04/2017 5 | activity 6 | 2/04/2015 5 | activity 2 | 2/04/2016 6 | activity 1 | 2/04/2018 </code></pre> <p>i have too...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for filter by conditions and columns names:</p> <pre><code>mask = (df['Date'].dt.year == 2015) df1 = df.loc[mask &amp; (df['ACTIVITY'] == 'activity 1'), ['ID','Da...
python|pandas
1
369,269
68,606,598
Value. Error when doing a string strip and attempting to convert object column to an integer in python
<p>I am attempting to strip out any characters other than numbers in a column and then convert that column from an object to integer, but I am receiving an error message.</p> <pre><code>data.dtypes Column1 object </code></pre> <p>the column of interest has numbers but also <code>','</code> in it which I belie...
<p>try this :</p> <pre><code>data['Column1'] = data['Column1'].str.replace(&quot;,&quot;, &quot;&quot;).astype(int) </code></pre>
python|pandas|numpy
1
369,270
68,790,081
Selecting explicit cells from pd.DataFrame via .at with MultiIndex
<p>I am having a MultiIndex based pd.DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = pd.DataFrame([[2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]], index=pd.MultiIndex.from_tuples([ (pd.Timestamp('2019-07-01 23:00:00'), pd.Timestamp('2019-07-01 23:00:00'), 0), ...
<p>We can still use <code>loc</code> to assign the single cell value by creating the intermediate series having the same index corresponding to the cell that needs to be updated. As a side note, storing complex objects in pandas columns is generally not a good practice as you will loose the benefits of vectorization.</...
python|pandas|dataframe|multi-index
5
369,271
68,568,527
create excel file from DataFrame and allow download in flask, error: file format/extension not valid
<p>I've created a simple Flask app that turns a Pandas Dataframe into an excel file. The file gets downloaded when I go to the link, however, I'm just getting the following error once I try and open the file:</p> <p><code>Excel cannot open the file 'df.xlsx' because the file format or file extension is not valid. Verif...
<p>The problem is that you're passing the dataframe to <code>ExcelWriter</code>'s <code>path</code> parameter instead of the <code>BytesIO</code> object (<code>output</code>).</p> <pre><code>writer = pd.ExcelWriter(df, engine='xlsxwriter') </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference...
python|pandas|flask|xlsxwriter
2
369,272
68,471,877
Tone sweep from array of frequencies with python
<p>I have array with frequency values and want to generate wav file with tone that sweeps between given values. Say</p> <pre><code>freqs = [100, 100, 200, 400, 1000, 100, 50] duration = 7 </code></pre> <p>I want WAV with duration of 7 seconds. So from T=0 to T=1s tone should be 100Hz, from T=1 to T=2 sweeps from 100Hz ...
<p>Here's how you can do this for two arbitrary frequencies:</p> <pre><code>import numpy as np from scipy.signal import chirp from scipy.io.wavfile import write interval_length = 1 # in seconds fs = 16000 # sampling of your signal f0 = 100 # frequency 1 f1 = 200 # frequency 2 t = np.linspace(0, interval_length, in...
python|numpy|audio|scipy|signal-processing
2
369,273
68,610,006
Pandas DataFrame Dividing a column by itself taking first element and divide all the rows and so on
<p>I have a DataFrame from Pandas:</p> <pre><code>import pandas as pd data1 = {&quot;a&quot;:[1.,3.,5.,2.]} df1 = pd.DataFrame(data1) </code></pre> <p>df1:</p> <pre><code> a 0 1.0 1 3.0 2 5.0 3 2.0 </code></pre> <p>Now I want to iterate over the rows. For every row, divided by the first elements of the sam...
<p>You can use <code>numpy</code> to increase the speed of the process:</p> <pre><code>&gt;&gt;&gt; df1 a a_1 a_2 0 1.0 1 3.0 2 5.0 3 2.0 </code></pre> <pre><code>import numpy as np a = np.hstack(df1.values) m = np.repeat(a, len(a)).reshape((a.shape[0], -1)) df = pd.DataFrame(a / m, columns=df1.columns...
python|pandas|dataframe
3
369,274
68,725,646
Styled pandas dataframe in Dash-Plotly
<p>I have pandas data frame and am using the &quot;df_styled = df.style.apply(...)&quot; method to style the values in data frame conveniently (in a Jupyter Notebook). However, I am unable to display this styled output when using Dash-Plotly dashboard.</p> <p>Can someone suggest anything?</p> <p>I have tried df_styled....
<p>Instead of directly using the styled components of Pandas, I would recommend the below</p> <ol> <li>Transform your dataframe to a plotly-dash datatable</li> <li>Format the dash datatable based on the plotly-dash documentation.</li> </ol> <p>an example code would be as below</p> <pre><code> mytable = dash_table.Data...
python|pandas|jupyter-notebook|plotly-dash
0
369,275
68,583,045
get partial string contained in "()" from a pandas DataFrame
<p>I have a df:</p> <pre><code> MinMaleTA 28 888(G2M) 29 888(AAM) 30 888(G2M) 31 888(G2M) 32 888(AAM) 33 888(G2M) 34 888(G2M) 35 888(AAM) 36 888(G2M) 37 888(G2M) 38 888(G2M) 39 888(G2M) 40 888(AAM) 41 888(G2M) 42 888(G2M) 43 888(G2M) </code></pre> <p>sometimes more ...
<p>Use <code>str.extract</code> method with a regex:</p> <pre><code>&gt;&gt;&gt; df['MinMaleTA'].str.extract(r'\((.*)\)') 0 28 G2M 29 AAM 30 G2M 31 G2M 32 AAM 33 G2M 34 G2M 35 AAM 36 G2M 37 G2M 38 G2M 39 G2M 40 AAM 41 G2M 42 G2M 43 G2M </code></pre> <p><code>\(</code> and <code>\)</code> match the...
python|pandas|dataframe|numpy
1
369,276
68,461,656
Correct application of numpy array dimensions
<p>I am in the process of collecting 3D-coordinates of multiple key points of one person's or multiple people's body over time. This data needs to be collected in one data set. This basically leads to an input for each frame consisting of one or multiple 19x3 matrices. The data set structure is supposed to look as foll...
<p>If you know the max number of 19x3 matrices in each frame, then you could set up the outer size and put empty matrices (or matrices of 0) where you don't have data. I think you might want to use pandas dataframe and take advantage of the indexing to make it easier to access your data later on.</p>
python|numpy|numpy-ndarray
1
369,277
68,554,267
Excessive disk writes when using numpy.memmap
<p>I have implemented a file-backed HashTable using <a href="https://numpy.org/doc/stable/reference/generated/numpy.memmap.html" rel="nofollow noreferrer">numpy.memmap</a>. It appears to be functioning correctly, however, I notice that on Linux both KSysGuard and SMART are reporting ridiculous IO Write amounts. About 5...
<p><code>memmap</code> work by mapping <strong>pages</strong> in virtual memory (typically to physical memory pages or storage device ones like in your case). On most platforms, the size of pages is at least 4 KiB. As a result, any write in a page may cause the whole page to be updated.</p> <p>SSDs and more generally <...
python|python-3.x|linux|numpy|numpy-memmap
1
369,278
68,785,645
How to add a title to a pandas dataframe plot
<p>Able to create 2 nice time series graphs, but <code>plot.title()</code> is not working. How can this be fixed?</p> <pre><code>import pandas as pd import datetime import matplotlib.pyplot as plt if __name__ == '__main__': index_data = pd.read_csv('comparison_dataset.csv') index_data['DATE'] = pd.to_dateti...
<p>Your <code>plt.title</code> call happens before the figure is created (with <code>plt.figure()</code>). This cannot work. You should move the <code>plt.title</code> command after the graph <code>df.plot()</code>.</p> <p>Also, if you want a <strong>figure</strong> title, the command is <code>plt.suptitle</code>. <cod...
python|pandas|matplotlib
1
369,279
68,807,139
Convert Duration Column to integer value
<p>I have a pandas dataframe with a duration column, they're currently of the object type with entries like 01:15:12 which means 1 hour and 15 minutes and 12 seconds, not the time. I want to strip the seconds off and convert these values to 1.25 because 15 minutes/60 minutes in an hour is .25 hours. Any suggestions? Th...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>pandas.to_timedelta</code></a>:</p> <pre><code>pd.to_timedelta(df['COLUMN']).dt.floor('T').dt.total_seconds()/3600 </code></pre>
python-3.x|pandas|dataframe|datetime|time
0
369,280
68,459,352
Python Dataframe Convert string to list type
<p>I have a CSV file coming from the field. It has the data in a peculiar format. That is, a list of values in string format. I want to convert it to the list type</p> <p>My code:</p> <pre><code>df = pd.DataFrame({'x':['-1,0,1,2,10','1.5,2,4,5'],'y':['2.5,2.4,2.3,1.5,0.1','5,4.5,3,-0.1']}) df = x ...
<p><code>applymap</code> with <code>ast.literal_eval</code> would be the fastest option</p> <pre><code>import ast df.applymap(ast.literal_eval) </code></pre> <p>Note this will produce tuples in output, although it doesn't matter but if you specifically need lists in your output then we can chain another <code>applymap...
python|pandas|dataframe
1
369,281
68,639,180
list of Bytes object to dataframe
<p>I have a list of Bytes (strings) which is separated by &quot;\n&quot;. I want to create a data frame from the list, and to separate each element to 15 columns. I have succeeded to separate the rows but I'm getting 1 column instead of 15.</p> <pre><code>from io import BytesIO df = pd.read_csv(BytesIO(b'\n'.join(tmp))...
<p>From your output it looks like your <code>tmp</code> list contains <code>\t</code> characters already, which would imply that the <code>\t</code> character is the separator in the data and not <code>\n</code> as you have specified. It is unlikely that <code>\n</code> is a separator between columns, which is what the...
python|pandas|dataframe
1
369,282
68,453,246
Creating a sub-set of data having only null values
<p>I have a data as under in a pandas dataframe [Original shape of the data : 149347 rows and 2 columns]. Purpose includes a text/strings and employeeID includes floats.</p> <p><a href="https://i.stack.imgur.com/Elmi9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Elmi9.png" alt="enter image descrip...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>print(df[df.Purpose.eq(&quot;&quot;)]) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> Purpose Employee 2 3 4 5 </code></pre> <hr /> <p><code>df</code> used:</p> <pre class="lang-none prettyprin...
python|pandas|dataframe
1
369,283
68,561,499
How to unit test the columns names are valid for a function that reads data with `pandas.read_sql()`?
<p>I have a function to read data from a MySQL database:</p> <pre><code>def example(mysql_engine) -&gt; DataFrame: query = &quot;&quot;&quot;SELECT col_1 FROM xxx.xxx&quot;&quot;&quot; df = pandas.read_sql(query, mysql_engine) return df </code></pre> <p><code>mysql_engine</code> is returned by another func...
<p>You can use <code>assert col_1 in df.columns</code> for the unit tests.</p> <p>For the Database engine, you can use a mock object. You can check <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow noreferrer">this link</a> from the standard library.</p>
python|mysql|pandas|unit-testing|read-sql
0
369,284
68,544,825
Python: how to groupby a dataframe with column name numbered for the unique values of a column?
<p>I have a dataframe that looks like the following where I have different number of <code>case</code> and 3 unique values for <code>val</code>.</p> <pre><code>df case val 0 0 x 1 0 y 2 0 z 3 1 x 4 1 z 5 2 y </code></pre> <p>Now I would like to have ...
<p>Use <code>pivot</code>:</p> <pre><code>out = df.pivot(index='case', columns='val', values='val') out.columns = [f'val{i}' for i in range(len(out.columns))] </code></pre> <pre><code>&gt;&gt;&gt; out val0 val1 val2 case 0 x y z 1 x NaN z 2 NaN y NaN </code></pre>
python|pandas
2
369,285
68,656,156
Is there a way to stop to_dict() from updating strings to datetime?
<p>I'm trying to develop a general solution to upload data from a dataframe to a MySQL table. The MySQL insert statement requires a ON DUPLCIATE KEY UPDATE so I can't just use to_sql(). I have it working fairly well, except in some cases to_dict() is converting date strings ('YYYY-MM-DD') to datetimes which can't be ...
<p>After you import your df into python</p> <pre><code>df['column'].astype(str) </code></pre> <p>See if this works, I don't have enough info to test this myself. Regardless the pandas.DataFrame.astype function will probably be useful. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame....
python|pandas
0
369,286
68,659,794
Python Transpose/Stack multiple columns
<p>Have a number of people that return responses to three questions.</p> <p>These three questions are asked numerous times, the issue is new responses are recorded as new columns.</p> <p><a href="https://i.stack.imgur.com/0uewk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0uewk.png" alt="Dataset" ...
<p>With a little renaming to add a suffix to the base <code>stubnames</code>, we can the use <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>pd.wide_to_long</code></a>:</p> <pre><code># Add Suffix to base Q1 Q2 Q3 df = df.rename(columns=dict(zip(['Q1', 'Q2...
python|pandas
1
369,287
68,635,970
Cylindrically symmetric magnetic field
<p>I want to plot the motion of a positive charge in a cylindrically symmetric magnetic field. <br> I am assuming a cylinder around the z-axis, with the magnetic field going in clockwise direction. The B-field has magnitude of 6T and the distance R from the z-axis is 3m. The charged particle is launched in positive dir...
<p>With <code>solve_ivp()</code>:</p> <p>There are only two functions, the first one, <code>B()</code> takes care of the geometry of the magnetic field (rotationally invariant relative to the z axis and radially invariant, with always the same magnitude at each point), and the second one <code>f()</code> takes care of ...
python|numpy|physics|ode
1
369,288
68,827,675
Sorting a pandas dataframe by a column containing numbers and text
<p>I have a pandas dataframe that I want to sort by one of the columns. Problem is, the data that needs to be sorted looks like this: &quot;'Number 1' - Specimen 'Number 2'&quot;. I want to sort by 'Number 1' first, and then 'Number 2'.</p> <p>An example:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Name': [...
<p>I convert the 'Name' column to a list of 2 numbers and then sort the column and then return the index.</p> <pre><code>index = df['Name'].apply(lambda x: list(map(int,x.split('- Specimen')))).argsort().to_list() df.iloc[index] </code></pre>
python|pandas
3
369,289
68,794,425
How to convert multilevel columns to multilevel index
<p>I have a dataframe with multilevel columns such as this:</p> <pre><code> x1 x2 A B A B date 2021-01-01 11.82 22.88 11.83 22.93 2021-01-02 11.95 22.78 12.02 23.08 2021-01-03 12.18 22.99 12.18 22.99 </code></pre> ...
<p>You can try stack with swaplevel:</p> <pre><code>df.rename_axis(['','sym'],axis=1).stack().swaplevel().sort_index()) </code></pre> <hr /> <pre><code> x1 x2 sym date A 2021-01-01 11.82 11.83 2021-01-02 11.95 12.02 2021-01-03 12.18 12.18 B 2021-01-01 22.88 ...
python|pandas|dataframe
2
369,290
68,869,465
How to make types in the rows of pandas dataframe to become the column header with result as row type?
<p>I have a df structured in following setting and would like to change it so that the types found in the column <code>type</code> are the the row readers with the original <code>result</code> as the row the new type column, condensing all <code>ids</code> into one row. For example, I would like to change the following...
<p>Try <code>pivot_table</code> with <code>rename_axis</code>:</p> <pre><code>&gt;&gt;&gt; df.pivot_table('result', ['id', 'name'], 'type', aggfunc=''.join).reset_index().rename_axis(columns=None) id name 1 2 3 0 A Apple X X X 1 B Banana Y Y NaN 2 C Cantaloupe NaN Z Z &gt...
python|pandas|dataframe
0
369,291
68,726,630
Accessing yahoo finance 104 stocks closing price but it appends the data in a single row instead of column
<pre><code> tickers = &quot;GNA.BO PDMJEPAPER.BO MEGH.BO REFEX.BO GULPOLY.BO TRIVENI.BO TCI.BO NUCLEUS.BO SHILPAMED.BO JUBILANT6.BO TITANBIO.BO INDOBORAX.BO POLYPLEX.BO MAZDALTD.BO KSE.BO RAJGLOWIR.BO MANORG.BO TATAMETALI.BO HIL.BO BAJAJST.BO TINPLATE.BO SESHAPAPER.BO DECCANCE.BO GESHIP.BO ESTER.BO DIAMINESQ.BO DENO...
<p>For long form data collection, I think it is easy to prepare an empty data frame, get the stock data sequentially, and add it to the empty data frame.</p> <pre><code>import yfinance as yf import pandas as pd tickers = &quot;GNA.BO PDMJEPAPER.BO MEGH.BO REFEX.BO GULPOLY.BO TRIVENI.BO TCI.BO NUCLEUS.BO&quot; tickerl...
python|pandas|stock|yfinance
0
369,292
68,535,750
square the numbers in lists in dictionaries in Python
<p>I have a dictionary created like:</p> <pre><code>di = { &quot;R&quot;: [{7, 9}, {5, 8}], &quot;N&quot;: [{6, 9}, {8, 8}], &quot;L&quot;: [{7, 9}, {5, 0}], &quot;P&quot;: [{0, 9}, {7, 8}] } </code></pre> <p>I want to square <code>dic[&quot;R&quot;]</code> numbers so the end result would be <code>{4...
<p>Note that these are not lists of ints, or lists of lists of ints, they are lists of sets of ints:</p> <pre><code>&gt;&gt;&gt; di = { ... &quot;R&quot;: [{7, 9}, {5, 8}], ... &quot;N&quot;: [{6, 9}, {8, 8}], ... &quot;L&quot;: [{7, 9}, {5, 0}], ... &quot;P&quot;: [{0, 9}, {7, 8}] ... } &gt;&gt;&gt; di...
python|python-3.x|list|numpy|math
2
369,293
68,635,750
replace nested 'for loop' with lambda in python
<p>I am working on one task where I need to check the cosine similarity between two dataframe columns. I am using two for loop to iterate over two columns of data1 and data2 respectively.</p> <pre><code>for i in range(0,len(input_df)): for j in range(0,len(data1)): ##check similarity ratio similari...
<p>To compute the cosine similarity between two vectors (your two columns), you could make use of NumPy:</p> <pre><code>import numpy as np def cosine_similarity(a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) cosine_similarity(input_df['Summary'], data1['Summary']) </code></pre> <p>However, b...
python|python-3.x|pandas
0
369,294
68,795,929
Pandas error: "None of [Index([' '], dtype='object')] are in the [columns]"
<p>For some reason, my code works when a list I am passing contains only integers. Using strings otherwise leads to the error in the title.</p> <p>Here is my code:</p> <pre><code>def get_support(self, data, itemset): return data[itemset].all(axis = 'columns').sum() # I also tried: return data.loc[:, itemset].al...
<p>You're going wrong here:</p> <p><code>data[itemset].all(axis = 'columns').sum()</code></p> <p>You can't <code>sum()</code> a string. You could run it through a data cleaning function first to make sure the list only has integers or floats.</p>
python|pandas
0
369,295
68,498,883
in python, spyder, i import sklearn, why it doesn't find 'classification' in 'sklearn.metric'?
<p>it sends : print(metrics.classification.accuracy_score(y_test, y_pred))</p> <p>AttributeError: module 'sklearn.metrics' has no attribute 'classification'</p> <p>it would appear that my sklearn can't import 'classification', but i can't find out why, can you help me please ?</p> <pre><code>from sklearn import metrics...
<p>Upgrade your sklearn should solve this.</p> <p>And it's called scikit-learn instead of sklearn in pip, do</p> <pre><code>pip install scikit-learn </code></pre> <p>If you already have it, try</p> <pre><code>pip install --upgrade scikit-learn </code></pre>
python|classification|sklearn-pandas
1
369,296
68,760,794
How to merge two dataframes without getting additional rows?
<p>Basically, I have two dataframes, the first one looks like this:</p> <p><img src="https://i.stack.imgur.com/QfXkK.png" alt="df1" /></p> <p>And the second one like this:</p> <p><img src="https://i.stack.imgur.com/0zBuj.png" alt="df2" /></p> <p>I want to get the columns &quot;lat&quot; and &quot;lnt&quot; of the secon...
<p>The <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">Pandas merge function</a> defaults to an inner join. Since you're looking to merge in the columns of <code>df2</code> to <code>df1</code>, you should use a left join. This will give you all the rows of <c...
python|pandas
1
369,297
68,727,367
Group the column values in a data frame
<p>I have a Json array with key value pairs like below</p> <pre><code>[ [ { &quot;value&quot;:&quot;Dimension1&quot;, &quot;formattedValue&quot;:&quot;Dimension1&quot; }, { &quot;value&quot;:&quot;In&quot;, &quot;formattedValue&quot;:&quot;In&quot; }, ...
<p>You can either use @AnuragDabas’ solution from the comments, combined with <code>.rename_axis()</code> to remove the index names:</p> <pre><code>&gt;&gt;&gt; df.set_index(['Dimension', 'Type']).rename_axis([None, None]) Amount1 Amount2 Dimension1 In 100 200 Out 30 4...
python|pandas|dataframe
2
369,298
68,749,984
How to change from an int to a string based on a condition
<p>Let's say that I have a data frame with a list of names and their gender. The default data frame has either a &quot;0&quot; or a &quot;1&quot; in the gender column for each name of the person in which the &quot;0&quot; implies that the person is a male while the &quot;1&quot; implies that the person is a female. How...
<p>Just do:</p> <pre><code>df['gender'] = df['gender'].map({1:'female', 0:'male'}) </code></pre> <p>OR</p> <pre><code>df.loc[(df.gender == 0), 'gender'] = 'male' df.loc[(df.gender == 1), 'gender'] = 'female' </code></pre>
python|pandas
1
369,299
68,856,313
Python Pandas pivot_table - Count of values in one column
<p>I am having a DataFrame (28 rows from the Titanic passenger list) which has a column &quot;Sex&quot; consisting of two values, &quot;Male&quot;, &quot;Female&quot;. I want to get the count of Males/Females</p> <p>The output should show &quot;Sex&quot; as Row labels(index) and the count (of Male/Female) in the second...
<p>It's just <code>df['Sex'].value_counts()</code></p>
python|pandas
1