category
stringclasses
107 values
title
stringlengths
15
179
question_link
stringlengths
59
147
question_body
stringlengths
53
33.8k
answer_html
stringlengths
0
28.8k
__index_level_0__
int64
0
1.58k
pytorch
What is the relationship between PyTorch and Torch?
https://stackoverflow.com/questions/44371560/what-is-the-relationship-between-pytorch-and-torch
<p>There are two PyTorch repositories :</p> <ul> <li><a href="https://github.com/hughperkins/pytorch" rel="noreferrer">https://github.com/hughperkins/pytorch</a></li> <li><a href="https://github.com/pytorch/pytorch" rel="noreferrer">https://github.com/pytorch/pytorch</a></li> </ul> <p>The first clearly requires Torch a...
<p>Here a short comparison on pytorch and torch.</p> <p><strong>Torch:</strong></p> <blockquote> <p>A Tensor library like <code>numpy</code>, unlike <code>numpy</code> it has strong GPU support.<br /> Lua is a wrapper for Torch (Yes! you need to have a good understanding of Lua), and for that you will need LuaRocks pac...
534
pytorch
How do I display a single image in PyTorch?
https://stackoverflow.com/questions/53623472/how-do-i-display-a-single-image-in-pytorch
<p>How do I display a PyTorch <code>Tensor</code> of shape <code>(3, 224, 224)</code> representing a 224x224 RGB image? Using <code>plt.imshow(image)</code> gives the error:</p> <blockquote> <p>TypeError: Invalid dimensions for image data</p> </blockquote>
<p>Given a <code>Tensor</code> representing the image, use <a href="https://pytorch.org/docs/stable/generated/torch.permute.html#torch.permute" rel="nofollow noreferrer"><code>.permute()</code></a> to put the channels as the last dimension when passing them to matplotlib:</p> <pre><code>plt.imshow(tensor_image.permute(...
535
pytorch
Is .data still useful in pytorch?
https://stackoverflow.com/questions/51743214/is-data-still-useful-in-pytorch
<p>I'm new to pytorch. I read much pytorch code which heavily uses tensor's <code>.data</code> member. But I search <code>.data</code> in the official document and Google, finding little. I guess <code>.data</code> contains the data in the tensor, but I don't know when we need it and when not? </p>
<p><code>.data</code> was an attribute of <code>Variable</code> (object representing <code>Tensor</code> with history tracking e.g. for automatic update), not <code>Tensor</code>. Actually, <code>.data</code> was giving access to the <code>Variable</code>'s underlying <code>Tensor</code>.</p> <p>However, since PyTorch...
536
pytorch
Install specific PyTorch version (pytorch==1.0.1)
https://stackoverflow.com/questions/64062637/install-specific-pytorch-version-pytorch-1-0-1
<p>I'm trying to install specific PyTorch version under conda env:</p> <p>Using pip:</p> <pre><code>pip3 install pytorch==1.0.1 WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue....
<p>You can download/install the version you like from the official <a href="https://anaconda.org/pytorch/pytorch/files?version=1.0.1" rel="noreferrer">Pytorch's Conda package</a>. the link you specified is an old version and is not supported/updated for quit some time now!.<br /> Install your desired version like this ...
537
pytorch
What are Torch Scripts in PyTorch?
https://stackoverflow.com/questions/53900396/what-are-torch-scripts-in-pytorch
<p>I've just found that PyTorch docs expose something that is called <a href="https://pytorch.org/docs/stable/jit.html?highlight=model%20features" rel="noreferrer">Torch Scripts</a>. However, I do not know:</p> <ul> <li>When they should be used?</li> <li>How they should be used?</li> <li>What are their benefits?</li> ...
<p>Torch Script is one of two modes of using the PyTorch <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation" rel="noreferrer">just in time compiler</a>, the other being <a href="https://pytorch.org/docs/stable/jit.html#torch.jit.trace" rel="noreferrer">tracing</a>. The benefits are explained in the linked ...
538
pytorch
PyTorch: What is numpy.linalg.multi_dot() equivalent in PyTorch
https://stackoverflow.com/questions/64520994/pytorch-what-is-numpy-linalg-multi-dot-equivalent-in-pytorch
<p>I am trying to perform matrix multiplication of multiple matrices in PyTorch and was wondering what is the equivalent of <code>numpy.linalg.multi_dot()</code> in PyTorch?</p> <p>If there isn't one, what is the next best way (in terms of speed and memory) I can do this in PyTorch?</p> <p>Code:</p> <pre><code>import n...
<p>~~Looks like one can send tensors into multi_dot~~</p> <p>Looks like the numpy implementation casts everything into numpy arrays. If your tensors are on the cpu and detached this should work. Otherwise, the conversion to numpy would fail.</p> <p>So in general - likely there isn't an alternative. I think your best sh...
539
pytorch
Install PyTorch from requirements.txt
https://stackoverflow.com/questions/60912744/install-pytorch-from-requirements-txt
<p>Torch documentation says use</p> <pre><code>pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html </code></pre> <p>to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do <code>pip install -r req.txt</code>, it...
<p>Add <code>--find-links</code> in <code>requirements.txt</code> before torch</p> <pre><code>--find-links https://download.pytorch.org/whl/torch_stable.html torch==1.2.0+cpu </code></pre> <p>Source: <a href="https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171" rel="noreferrer">https://github.com/py...
540
pytorch
How Pytorch Tensor get the index of specific value
https://stackoverflow.com/questions/47863001/how-pytorch-tensor-get-the-index-of-specific-value
<p>With python lists, we can do:</p> <pre><code>a = [1, 2, 3] assert a.index(2) == 1 </code></pre> <p>How can a pytorch tensor find the <code>.index()</code> directly?</p>
<p>I think there is no direct translation from <code>list.index()</code> to a pytorch function. However, you can achieve similar results using <code>tensor==number</code> and then the <code>nonzero()</code> function. For example:</p> <pre><code>t = torch.Tensor([1, 2, 3]) print ((t == 2).nonzero(as_tuple=True)[0]) </co...
541
pytorch
Installing PyTorch via Conda
https://stackoverflow.com/questions/49951846/installing-pytorch-via-conda
<p>Objective: Create a conda environment with pytorch and torchvision. Anaconda Navigator 1.8.3, python 3.6, MacOS 10.13.4.</p> <p>What I've tried:</p> <ul> <li>In Navigator, created a new environment. Tried to install pytorch and torchvision but could not because the UI search for packages does not find any packages...
<p>You seem to have installed PyTorch in your base environment, you therefore cannot use it from your other "pytorch" env.</p> <p>Either:</p> <ul> <li><p>directly create a new environment (let's call it <code>pytorch_env</code>) with PyTorch: <code>conda create -n pytorch_env -c pytorch pytorch torchvision</code></p>...
542
pytorch
What does `-1` of `view()` mean in PyTorch?
https://stackoverflow.com/questions/50792316/what-does-1-of-view-mean-in-pytorch
<p>As the question says, what does <code>-1</code> of <code>view()</code> do in PyTorch?</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a = torch.arange(1, 17) &gt;&gt;&gt; a tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16.]) &gt;&gt;&gt; ...
<p>Yes, it does behave like <code>-1</code> in <code>numpy.reshape()</code>, i.e. the actual value for this dimension will be inferred so that the number of elements in the view matches the original number of elements.</p> <p>For instance:</p> <pre class="lang-py prettyprint-override"><code>import torch x = torch.aran...
543
pytorch
How can i process multi loss in pytorch?
https://stackoverflow.com/questions/53994625/how-can-i-process-multi-loss-in-pytorch
<p><a href="https://i.sstatic.net/yBrXW.png" rel="noreferrer"><img src="https://i.sstatic.net/yBrXW.png" alt="enter image description here"></a></p> <p>Such as this, I want to using some auxiliary loss to promoting my model performance.<br/> Which type code can implement it in pytorch?</p> <pre><code>#one loss1.backw...
<p>First and 3rd attempt are exactly the same and correct, while 2nd approach is completely wrong.</p> <p>In Pytorch, low layer gradients are <strong>Not</strong> &quot;overwritten&quot; by subsequent <code>backward()</code> calls, rather they are accumulated, or summed. This makes first and 3rd approach identical, th...
544
pytorch
Indexing Pytorch tensor
https://stackoverflow.com/questions/59154920/indexing-pytorch-tensor
<p>I have a Pytorch code which generates a Pytorch tensor in each iteration of for loop, all of the same size. I want to assign each of those tensors to a row of new tensor, which will include all the tensors at the end. In other works something like this</p> <pre><code>for i=1:N: X = torch.Tensor([[1,2,3], [3,2,5]]...
<p>You can concatenate the tensors using <a href="https://pytorch.org/docs/stable/torch.html#torch.cat" rel="nofollow noreferrer"><code>torch.cat</code></a>:</p> <pre class="lang-py prettyprint-override"><code>tensors = [] for i in range(N): X = torch.tensor([[1,2,3], [3,2,5]]) tensors.append(X) Y = torch.cat(tens...
545
pytorch
Pytorch doesn&#39;t support one-hot vector?
https://stackoverflow.com/questions/55549843/pytorch-doesnt-support-one-hot-vector
<p>I am very confused by how Pytorch deals with one-hot vectors. In this <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="noreferrer">tutorial</a>, the neural network will generate a one-hot vector as its output. As far as I understand, the schematic structure of the neural network in t...
<p>PyTorch states in its documentation for <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss" rel="noreferrer"><code>CrossEntropyLoss</code></a> that</p> <blockquote> <p>This criterion expects a class index (0 to C-1) as the target for each value of a 1D tensor of size minibatch</p> </blockquot...
546
pytorch
Run Pytorch examples with Pytorch build from source
https://stackoverflow.com/questions/76260489/run-pytorch-examples-with-pytorch-build-from-source
<p>I have build pytorch 2.0.1 from source. Using cuda 11.7, cudnn v8, and the driver for the nvidia GPU is 515.43.04 (CUDA version 11.7). Altough Pytorch seems to build successfully when I am trying to run examples downloaded from <a href="https://github.com/pytorch/examples" rel="nofollow noreferrer">github</a> I see ...
<p>The issue was that there was a local installed PyTorch.</p>
547
pytorch
Hyperparameter optimization for Pytorch model
https://stackoverflow.com/questions/44260217/hyperparameter-optimization-for-pytorch-model
<p>What is the best way to perform hyperparameter optimization for a Pytorch model? Implement e.g. Random Search myself? Use Skicit Learn? Or is there anything else I am not aware of?</p>
<p>Many researchers use <a href="http://ray.readthedocs.io/en/latest/tune.html" rel="noreferrer">RayTune</a>. It's a scalable hyperparameter tuning framework, specifically for deep learning. You can easily use it with any deep learning framework (2 lines of code below), and it provides most state-of-the-art algorithms,...
548
pytorch
Why do we &quot;pack&quot; the sequences in PyTorch?
https://stackoverflow.com/questions/51030782/why-do-we-pack-the-sequences-in-pytorch
<p>I was trying to replicate <a href="https://discuss.pytorch.org/t/simple-working-example-how-to-use-packing-for-variable-length-sequence-inputs-for-rnn/2120" rel="noreferrer">How to use packing for variable-length sequence inputs for rnn</a> but I guess I first need to understand why we need to &quot;pack&quot; the s...
<p>I have stumbled upon this problem too and below is what I figured out.</p> <p>When training RNN (LSTM or GRU or vanilla-RNN), it is difficult to batch the variable length sequences. For example: if the length of sequences in a size 8 batch is [4,6,8,5,4,3,7,8], you will pad all the sequences and that will result in ...
549
pytorch
No N-dimensional tranpose in PyTorch
https://stackoverflow.com/questions/44841654/no-n-dimensional-tranpose-in-pytorch
<p>PyTorch's <code>torch.transpose</code> function only transposes 2D inputs. Documentation is <a href="http://pytorch.org/docs/master/torch.html#torch.transpose" rel="noreferrer">here</a>.</p> <p>On the other hand, Tensorflow's <code>tf.transpose</code> function allows you to transpose a tensor of <code>N</code> arbi...
<p>It's simply called differently in pytorch. <a href="http://pytorch.org/docs/master/tensors.html#torch.Tensor.permute" rel="noreferrer">torch.Tensor.permute</a> will allow you to swap dimensions in pytorch like tf.transpose does in TensorFlow.</p> <p>As an example of how you'd convert a 4D image tensor from NHWC to ...
550
pytorch
How to build pytorch source?
https://stackoverflow.com/questions/71075872/how-to-build-pytorch-source
<p>When I use pytorch, it showed that my the cuda version pytorch used and cuda version of system are inconsistent, so I need rebuild pytorch from source.</p> <pre class="lang-sh prettyprint-override"><code># install dependency pip install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_exten...
<p>Building pytorch from source is not trivial, there is extensive documentation for it here<a href="https://github.com/pytorch/pytorch#from-source" rel="nofollow noreferrer">enter link description here</a> . However I think you should try to either install directly a an older pytorch version compatible with your syste...
551
pytorch
How does one use Pytorch (+ cuda) with an A100 GPU?
https://stackoverflow.com/questions/66992585/how-does-one-use-pytorch-cuda-with-an-a100-gpu
<p>I was trying to use my current code with an A100 gpu but I get this error:</p> <pre><code>---&gt; backend='nccl' /home/miranda9/miniconda3/envs/metalearningpy1.7.1c10.2/lib/python3.8/site-packages/torch/cuda/__init__.py:104: UserWarning: A100-SXM4-40GB with CUDA capability sm_80 is not compatible with the current P...
<p>From the link <a href="https://pytorch.org/get-started/locally/" rel="noreferrer">pytorch site</a> from @SimonB 's answer, I did:</p> <pre><code>pip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html </code></pre> <p>This solved the problem f...
552
pytorch
PyTorch: new_ones vs ones
https://stackoverflow.com/questions/52866333/pytorch-new-ones-vs-ones
<p>In PyTorch what is the difference between <code>new_ones()</code> vs <code>ones()</code>. For example,</p> <pre><code>x2.new_ones(3,2, dtype=torch.double) </code></pre> <p>vs </p> <pre><code>torch.ones(3,2, dtype=torch.double) </code></pre>
<p>For the sake of this answer, I am assuming that your <code>x2</code> is a previously defined <code>torch.Tensor</code>. If we then head over to the <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.new_ones" rel="noreferrer">PyTorch documentation</a>, we can read the following on <code>new_ones()</c...
553
pytorch
Pytorch Installation for different CUDA architectures
https://stackoverflow.com/questions/68496906/pytorch-installation-for-different-cuda-architectures
<p>I have a Dockerfile which installs PyTorch library from the source code.</p> <p>Here is the snippet from Dockerfile which performs the installation from source code of pytorch</p> <pre><code>RUN cd /tmp/ \ &amp;&amp; git clone https://github.com/pytorch/pytorch.git \ &amp;&amp; cd pytorch \ &amp;&amp; git submod...
<p><strong>TL;DR</strong> The version you choose needs to correlate with your hardware, otherwise the code won't run, even if it compiles. So for example, if you want it to run on an RTX 3090, you need to make sure <code>sm_80</code>, <code>sm_86</code> or <code>sm_87</code> is in the list. <code>sm_87</code> can do th...
554
pytorch
Pytorch Cuda for ubuntu 20.04
https://stackoverflow.com/questions/71822979/pytorch-cuda-for-ubuntu-20-04
<p>I'm trying to get pytorch with cuda 10 compatibility via : conda install pytorch torchvision cudatoolkit=10.2 -c pytorch from(<a href="https://discuss.pytorch.org/t/pytorch-with-cuda-11-compatibility/89254" rel="nofollow noreferrer">https://discuss.pytorch.org/t/pytorch-with-cuda-11-compatibility/89254</a>) but ther...
<p>So I was running WSL2 and didn't shut down for many days. A reboot fixed the issue.</p>
555
pytorch
How to load a list of numpy arrays to pytorch dataset loader?
https://stackoverflow.com/questions/44429199/how-to-load-a-list-of-numpy-arrays-to-pytorch-dataset-loader
<p>I have a huge list of numpy arrays, where each array represents an image and I want to load it using torch.utils.data.Dataloader object. But the documentation of torch.utils.data.Dataloader mentions that it loads data directly from a folder. How do I modify it for my cause? I am new to pytorch and any help would be ...
<p>I think what DataLoader actually requires is an input that subclasses <code>Dataset</code>. You can either write your own dataset class that subclasses <code>Dataset</code>or use <code>TensorDataset</code> as I have done below:</p> <pre><code>import torch import numpy as np from torch.utils.data import TensorDataset...
556
pytorch
pytorch tensorboard &quot;add_embedding error&quot;
https://stackoverflow.com/questions/66490589/pytorch-tensorboard-add-embedding-error
<p>everyone. I'm stuck in using tensorboard in pytorch. The point is add_embedding method makes the error like below:</p> <pre><code>Traceback (most recent call last): File &quot;test2.py&quot;, line 126, in &lt;module&gt; writer.add_embedding(features, metadata=class_labels, label_img = images.unsqueeze(1)) Fi...
<p>This is a nasty little bug that someone needs to patch.. There's a conversation about it <a href="https://github.com/pytorch/pytorch/issues/47139" rel="nofollow noreferrer">here</a></p> <p>I was able to fix it by adding:</p> <pre><code>import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile </code>...
557
pytorch
What is volatile variable in Pytorch
https://stackoverflow.com/questions/49837638/what-is-volatile-variable-in-pytorch
<p>What is volatile attribute of a Variable in Pytorch? Here's a sample code for defining a variable in PyTorch.</p> <pre><code>datatensor = Variable(data, volatile=True) </code></pre>
<p>Basically, set the input to a network to volatile if you are doing inference only and won't be running backpropagation in order to conserve memory.</p> <p>From the <a href="http://pytorch.org/docs/stable/notes/autograd.html#volatile" rel="noreferrer">docs</a>:</p> <blockquote> <p>Volatile is recommended for pure...
558
pytorch
PyTorch equivalence for softmax_cross_entropy_with_logits
https://stackoverflow.com/questions/46218566/pytorch-equivalence-for-softmax-cross-entropy-with-logits
<p>I was wondering is there an equivalent PyTorch loss function for TensorFlow's <code>softmax_cross_entropy_with_logits</code>?</p>
<blockquote> <p>is there an equivalent PyTorch loss function for TensorFlow's <code>softmax_cross_entropy_with_logits</code>?</p> </blockquote> <h3 id="torch.nn.functional.cross_entropy-ihhr"><code>torch.nn.functional.cross_entropy</code></h3> <p>This takes logits as inputs (performing <code>log_softmax</code> internal...
559
pytorch
Pytorch backpropagation
https://stackoverflow.com/questions/75745988/pytorch-backpropagation
<p>When there are max and absolute value operations in the pytorch model, how does pytorch implement the gradient descent of these operations during backpropagation please give a detail answer,thank you!</p>
<p><code>torch.abs</code> is non-differentiable only at 0, and it seems that pytorch implements a 0 derivative over some interval [-epsilon,+epsilon] near 0 <a href="https://discuss.pytorch.org/t/how-does-autograd-deal-with-non-differentiable-opponents-such-as-abs-and-max/34538" rel="nofollow noreferrer">https://discus...
560
pytorch
How does pytorch backprop through argmax?
https://stackoverflow.com/questions/54969646/how-does-pytorch-backprop-through-argmax
<p>I'm building Kmeans in pytorch using gradient descent on centroid locations, instead of expectation-maximisation. Loss is the sum of square distances of each point to its nearest centroid. To identify which centroid is nearest to each point, I use argmin, which is not differentiable everywhere. However, pytorch is...
<p>As alvas noted in the comments, <code>argmax</code> is not differentiable. However, once you compute it and assign each datapoint to a cluster, the derivative of loss with respect to the location of these clusters is well-defined. This is what your algorithm does.</p> <p>Why does it work? If you had only one cluste...
561
pytorch
Pytorch install with anaconda error
https://stackoverflow.com/questions/45906706/pytorch-install-with-anaconda-error
<p>I get this error:</p> <pre><code>C:\Users&gt;conda install pytorch torchvision -c soumith Fetching package metadata ............. PackageNotFoundError: Package missing in current win-64 channels: - pytorch </code></pre> <p>I got <code>conda install pytorch torchvision -c soumith</code> from <a href="http://pyto...
<p>Use the following commands to install pytorch on windows</p> <p>for Windows 10 and Windows Server 2016, CUDA 8</p> <pre><code>conda install -c peterjc123 pytorch cuda80 </code></pre> <p>for Windows 10 and Windows Server 2016, CUDA 9</p> <pre><code>conda install -c peterjc123 pytorch cuda90 </code></pre> <p>for ...
562
pytorch
Pytorch tensor indexing
https://stackoverflow.com/questions/57071002/pytorch-tensor-indexing
<p>I am currently working on converting some code from tensorflow to pytorch, I encountered problem with <a href="https://www.tensorflow.org/api_docs/python/tf/gather" rel="nofollow noreferrer"><code>tf.gather</code></a> func, there is no direct function to convert it in pytorch.</p> <p>What I am trying to do is basic...
<p>I think you are looking for <a href="https://pytorch.org/docs/stable/torch.html#torch.gather" rel="nofollow noreferrer"><code>torch.gather</code></a></p> <pre class="lang-py prettyprint-override"><code>out = torch.gather(A, 1, B[..., None].expand(*B.shape, A.shape[-1])) </code></pre>
563
pytorch
Where do I get a CPU-only version of PyTorch?
https://stackoverflow.com/questions/51730880/where-do-i-get-a-cpu-only-version-of-pytorch
<p>I'm trying to get a basic app running with Flask + PyTorch, and host it on Heroku. However, I run into the issue that the maximum slug size is 500mb on the free version, and PyTorch itself is ~500mb.</p> <p>After some google searching, someone wrote about finding a cpu-only version of PyTorch, and using that, which ...
<p>Per the Pytorch website, you can install <code>pytorch-cpu</code> with</p> <pre><code>conda install pytorch-cpu torchvision-cpu -c pytorch </code></pre> <p>You can see from the files on <a href="https://anaconda.org/pytorch/pytorch-cpu/files" rel="noreferrer">Anaconda cloud</a>, that the size varies between 26 and...
564
pytorch
PyTorch and PyTorch-operator kubeflow pipelines
https://stackoverflow.com/questions/66201581/pytorch-and-pytorch-operator-kubeflow-pipelines
<p>I am trying to integrate pytorch and pytorch-operators into kubeflow pipelines and I am not able to get a good resource for both. Is this possible in the current implementation?</p> <p>I understand that TFJob and PyTorchJob all run training containers on top of a kubernetes cluster but I am trying to integrate them ...
565
pytorch
Pytorch version for cuda 12.2
https://stackoverflow.com/questions/76678846/pytorch-version-for-cuda-12-2
<p>I am unable to find the Pytorch version for cuda driver 12.2. Can anyone please guide me where can I find any material that helps.</p> <p>I have installed currently pytorch version 11.7. While training the model i am facing following error.</p> <p>** RuntimeError(CUDA_MISMATCH_MESSAGE.format(cuda_str_version, torch....
<p>You can install the nightly build. Note you should have <code>cudnn</code> installed already, I am using cudnn v8.9.3. The 12.1 PyTorch version works fine with CUDA v12.2.2:</p> <p><code>conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch-nightly -c nvidia</code></p>
566
pytorch
Pytorch custom activation functions?
https://stackoverflow.com/questions/55765234/pytorch-custom-activation-functions
<p>I'm having issues with implementing custom activation functions in Pytorch, such as Swish. How should I go about implementing and using custom activation functions in Pytorch?</p>
<p>There are <strong>four</strong> possibilities depending on what you are looking for. You will need to ask yourself two questions:</p> <p><strong>Q1)</strong> Will your activation function have learnable parameters?</p> <p>If <strong>yes</strong>, you have no choice but to create your activation function as an <code>...
567
pytorch
PyTorch / Gensim - How do I load pre-trained word embeddings?
https://stackoverflow.com/questions/49710537/pytorch-gensim-how-do-i-load-pre-trained-word-embeddings
<p>I want to load a pre-trained word2vec embedding with gensim into a PyTorch embedding layer.</p> <p>How do I get the embedding weights loaded by gensim into the PyTorch embedding layer?</p>
<p>I just wanted to report my findings about loading a gensim embedding with PyTorch.</p> <hr> <ul> <li><h2>Solution for PyTorch <code>0.4.0</code> and newer:</h2></li> </ul> <p>From <code>v0.4.0</code> there is a new function <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Embedding.from_pretrained" rel="...
568
pytorch
pytorch backports.functools_lru_cache conflict
https://stackoverflow.com/questions/53137588/pytorch-backports-functools-lru-cache-conflict
<p>I'm using <em>Windows 10</em>, and my the installation dir is: <code>anacoda2/python2.7/python3.6/opencv/cdua10/cudnn ....</code> </p> <p>Now I want to install pytorch, with this command: <code>conda install pytorch -c pytorch</code></p> <p>But as result I'm getting this error:</p> <pre><code>C:\Users\MM&gt;conda...
<p>I faced a similar problem while installing pytorch. I was able to resolve it by creating another environment on anaconda which had python version 3.6. </p>
569
pytorch
How to add a new dimension to a PyTorch tensor?
https://stackoverflow.com/questions/65470807/how-to-add-a-new-dimension-to-a-pytorch-tensor
<p>In NumPy, I would do</p> <pre class="lang-py prettyprint-override"><code>a = np.zeros((4, 5, 6)) a = a[:, :, np.newaxis, :] assert a.shape == (4, 5, 1, 6) </code></pre> <p>How to do the same in PyTorch?</p>
<pre><code>a = torch.zeros(4, 5, 6) a = a[:, :, None, :] assert a.shape == (4, 5, 1, 6) </code></pre>
570
pytorch
pytorch delete model from gpu
https://stackoverflow.com/questions/53350905/pytorch-delete-model-from-gpu
<p>I want to make a cross validation in my project based on Pytorch. And I didn't find any method that pytorch provided to delete the current model and empty the memory of GPU. Could you tell that how can I do it?</p>
<p>Freeing memory in PyTorch works as it does with the normal Python garbage collector. This means once all references to an <em>Python-Object</em> are gone it will be deleted.</p> <p>You can delete references by using the <a href="https://stackoverflow.com/questions/20847149/how-does-del-operator-work-in-list-in-pyth...
571
pytorch
Pytorch Install
https://stackoverflow.com/questions/74107561/pytorch-install
<p>I HAVE A ERROR IN INSTALLING PYTORCH: PLEASE HELP ME. CondaHTTPError: HTT P000 CONNECTION FAILED for url <a href="https://conda.anaconda.org/pytorch/win-64/current_repodata.json" rel="nofollow noreferrer">https://conda.anaconda.org/pytorch/win-64/current_repodata.json</a> Elapsed: -</p> <p>An HTTP error occurred whe...
<blockquote> <p>An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way</p> </blockquote> <p>The possible reason for HTTP error could be an unstable network connection or a corporate firewall.</p> <p>If it was an unstable network connectio...
572
pytorch
Pytorch 1.13 dataloader is significantly faster than Pytorch 2.0.1
https://stackoverflow.com/questions/77417920/pytorch-1-13-dataloader-is-significantly-faster-than-pytorch-2-0-1
<p>I've noticed that PyTorch 2.0.1 DataLoader is significantly slower than PyTorch 1.13 DataLoader, especially when the number of workers is set to something other than 0. I've done some research and found that this is due to a change in the way that PyTorch handles multiprocessing in version 2.0.1. In PyTorch 1.13, th...
573
pytorch
PyTorch is installed but not imported
https://stackoverflow.com/questions/53165990/pytorch-is-installed-but-not-imported
<p>I am trying to build PyTorch. Reference site:<a href="https://github.com/hughperkins/pytorch" rel="nofollow noreferrer">https://github.com/hughperkins/pytorch</a></p> <p>but, When we performed unit test, The following error occur.</p> <pre><code>ImportError while importing test module '/home/usr2/pytorch/test/test...
<p>In fact, you should do <code>import torch</code> instead of <code>import PyTorch</code><br> Here is what's work for me: (I installed it using conda)</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; torch.version &gt;&gt;&gt; &lt;module 'torch.version' from '/home/koke_cacao/miniconda3/envs/ml/lib/python3.6/si...
574
pytorch
Using pytorch Dataloader in pytorch kmeans
https://stackoverflow.com/questions/63348557/using-pytorch-dataloader-in-pytorch-kmeans
<p>I'm Trying to perform a Kmeans clusterization using the Pytorch-kmeans (<a href="https://github.com/subhadarship/kmeans_pytorch" rel="nofollow noreferrer">github</a>). I have aprox. 27M array with 512 elements each, the aprox. size of the numpy array is 51GB which is bigger than my GPU RAM (32GB). Is there a way I c...
575
pytorch
400% higher error with PyTorch compared with identical Keras model (with Adam optimizer)
https://stackoverflow.com/questions/73600481/400-higher-error-with-pytorch-compared-with-identical-keras-model-with-adam-op
<hr /> <p><strong>TLDR</strong>:</p> <p><em>A simple (single hidden-layer) feed-forward Pytorch model trained to predict the function <code>y = sin(X1) + sin(X2) + ... sin(X10)</code> substantially underperforms an identical model built/trained with Keras. Why is this so and what can be done to mitigate the difference ...
<p>The problem here is unintentional broadcasting in the PyTorch training loop.</p> <p>The result of a <code>nn.Linear</code> operation always has shape <code>[B,D]</code>, where <code>B</code> is the batch size and <code>D</code> is the output dimension. Therefore, in your <code>mean_squared_error</code> function <cod...
576
pytorch
pytorch compute pairwise difference: Incorrect result in NumPy vs PyTorch and different PyTorch versions
https://stackoverflow.com/questions/55884299/pytorch-compute-pairwise-difference-incorrect-result-in-numpy-vs-pytorch-and-di
<p>Suppose I have two arrays, and I want to calculate row-wise differences between every two rows of two matrices of the same shape as follows. This is how the procedure looks like in numpy, and I want to replicate the same thing in pytorch.</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,3],[4,5,6]]) &gt;&gt;&gt; b = ...
<p>The issue arises because of using <strong>PyTorch 0.1</strong>. If using PyTorch 1.0.1, the same operation of NumPy generalize to PyTorch without any modifications and issues. Here is a snapshot of the run in Colab.</p> <p><a href="https://i.sstatic.net/axKBu.png" rel="nofollow noreferrer"><img src="https://i.sstat...
577
pytorch
Anaconda always want to replace my GPU Pytorch version to CPU Pytorch version when updating
https://stackoverflow.com/questions/62630186/anaconda-always-want-to-replace-my-gpu-pytorch-version-to-cpu-pytorch-version-wh
<p>I have a newly installed Anaconda3 (version 2020.02) environment, and I have installed Pytorch GPU version by the command <code>conda install pytorch torchvision cudatoolkit=10.2 -c pytorch</code>. I have verified that my Pytorch indeed runs fine on GPU.</p> <p>However, whenever I update Anaconda by <code>conda upda...
<p>It's happening because, by default, conda prefers packages from a higher priority channel over any version from a lower priority channel. -- <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-channels.html" rel="nofollow noreferrer">conda docs</a></p> <p>You can solve this problem by se...
578
pytorch
how to install pytorch in python2.7?
https://stackoverflow.com/questions/57835948/how-to-install-pytorch-in-python2-7
<p>i am using python2.7 in virtual environment. i tried to install pytorch in python2.7 but i got error belows:</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-override"><code>Unsatisfi...
<p>Here's the link to the <a href="https://pytorch.org" rel="nofollow noreferrer">PyTorch official download page</a></p> <p>From here, you can choose the python version (2.7) and CUDA (None) and other relevant details based on your environment and OS.</p> <p>Other helpful links:</p> <ul> <li><a href="https://stackov...
579
pytorch
Unable to install Pytorch in Ubuntu
https://stackoverflow.com/questions/63272687/unable-to-install-pytorch-in-ubuntu
<p>I'm using the following command to install pytorch in my conda environment.</p> <pre><code>conda install pytorch=0.4.1 cuda90 -c pytorch </code></pre> <p>However, I'm getting the following error</p> <blockquote> <p>Solving environment: failed</p> <p>PackagesNotFoundError: The following packages are not available fro...
<p>Go directly to the pytorch website and follow the instructions for your setup and it will tell you exactly the command required to install - <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">pytorch - get started</a></p> <p>For example:</p> <p><a href="https://i.sstatic.net/D5XqP.png" rel=...
580
pytorch
Using pytorch Cuda on MacBook Pro
https://stackoverflow.com/questions/63423463/using-pytorch-cuda-on-macbook-pro
<p>I am using MacBook Pro (16-inch, 2019, macOS 10.15.5 (19F96))</p> <p>GPU</p> <ul> <li>AMD Radeon Pro 5300M</li> <li>Intel UHD Graphics 630</li> </ul> <p>I am trying to use Pytorch with Cuda on my mac.</p> <p>All of the guides I saw assume that i have Nvidia graphic card.</p> <p>I found this: <a href="https://github....
<h2>PyTorch now supports training using Metal.</h2> <p>Announcement: <a href="https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/" rel="noreferrer">https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/</a></p> <p>To get started, install the latest nightly build of PyTorch: <a h...
581
pytorch
PyTorch : error message &quot;torch has no [...] member&quot;
https://stackoverflow.com/questions/50319943/pytorch-error-message-torch-has-no-member
<p>Good evening, I have just installed PyTorch 0.4.0 and I'm trying to carry out the first tutorial "What is PyTorch?" I have written a Tutorial.py file which I try to execute with Visual Studio Code</p> <p>Here is the code :</p> <pre><code>from __future__ import print_function import torch print (torch.__version__)...
<p><em>In case you haven't got a solution to your problem or someone else encounters it.</em></p> <p>The error is raised because of Pylint (<em>Python static code analysis tool</em>) not recognizing <code>rand</code> as the member function. You can either configure Pylint to <em>ignore</em> this problem or you can whi...
582
pytorch
PyTorch and CUDA driver
https://stackoverflow.com/questions/52562352/pytorch-and-cuda-driver
<p>I have CUDA 9.2 installed. For example:</p> <pre><code>(base) c:\&gt;nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2018 NVIDIA Corporation Built on Wed_Apr_11_23:16:30_Central_Daylight_Time_2018 Cuda compilation tools, release 9.2, V9.2.88 </code></pre> <p>I installed PyTorch on Windows 1...
<p>Ever since <a href="https://github.com/pytorch/pytorch/releases/tag/v0.3.1" rel="nofollow noreferrer">https://github.com/pytorch/pytorch/releases/tag/v0.3.1</a>, PyTorch binary releases had removed support for old GPUs' with CUDA capability 3.0. According to <a href="https://en.wikipedia.org/wiki/CUDA" rel="nofollo...
583
pytorch
What is the difference between .pt, .pth and .pwf extentions in PyTorch?
https://stackoverflow.com/questions/59095824/what-is-the-difference-between-pt-pth-and-pwf-extentions-in-pytorch
<p>I have seen in some code examples, that people use .pwf as model file saving format. But in PyTorch documentation .pt and .pth are recommended. I used .pwf and worked fine for small 1->16->16 convolutional network.</p> <p>My question is what is the difference between these formats? Why is .pwf extension not even re...
<p>There are no differences between the extensions that were listed: <code>.pt</code>, <code>.pth</code>, <code>.pwf</code>. One can use whatever extension (s)he wants. So, if you're using <code>torch.save()</code> for saving models, then it by default uses python pickle (<code>pickle_module=pickle</code>) to save the ...
584
pytorch
pytorch versus autograd.numpy
https://stackoverflow.com/questions/62404451/pytorch-versus-autograd-numpy
<p>What are the big differences between pytorch and numpy, in particular, the autograd.numpy package? ( since both of them can compute the gradient automatically for you.) I know that pytorch can move tensors to GPU, but is this the only reason for choosing pytorch over numpy? While pytorch is well known for deep lear...
<p>I'm not sure if this question can be objectively answered, but besides the GPU functionality, it offers</p> <ul> <li>Parallelisation across GPUs</li> <li>Parallelisation across Machines</li> <li>DataLoaders / Manipulators incl. asynchronous pre-fetching</li> <li>Optimizers</li> <li>Predefined/Pretrained Models (can...
585
pytorch
PyTorch: How to get the shape of a Tensor as a list of int
https://stackoverflow.com/questions/46826218/pytorch-how-to-get-the-shape-of-a-tensor-as-a-list-of-int
<p>In numpy, <code>V.shape</code> gives a tuple of ints of dimensions of V.</p> <p>In tensorflow <code>V.get_shape().as_list()</code> gives a list of integers of the dimensions of V.</p> <p>In pytorch, <code>V.size()</code> gives a size object, but how do I convert it to ints?</p>
<p>For PyTorch v1.0 and possibly above:</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; var = torch.tensor([[1,0], [0,1]]) # Using .size function, returns a torch.Size object. &gt;&gt;&gt; var.size() torch.Size([2, 2]) &gt;&gt;&gt; type(var.size()) &lt;class 'torch.Size'&gt; # Similarly, using .shape &gt;&gt;&...
586
pytorch
Run pytorch in pyodide?
https://stackoverflow.com/questions/64358372/run-pytorch-in-pyodide
<p>Is there any way I can run the python library pytorch in pyodide? I tried installing pytorch with micropip but it gives this error message:</p> <blockquote> <p>Couldn't find a pure Python 3 wheel for 'pytorch'</p> </blockquote>
<p>In Pyodide micropip only allows to install pure python wheels (i.e. that don't have compiled extensions). The filename for those wheels ends with <code>none-any.whl</code> (see <a href="https://www.python.org/dev/peps/pep-0427/#file-name-convention" rel="noreferrer">PEP 427</a>).</p> <p>If you look at Pytorch wheels...
587
pytorch
PyTorch: Error 803: system has unsupported display driver / cuda driver combination (CUDA 11.7, pytorch 1.13.1)
https://stackoverflow.com/questions/75688024/pytorch-error-803-system-has-unsupported-display-driver-cuda-driver-combinat
<p>I can't get PyTorch to work.</p> <p>I have cuda and NVIDIA drivers installed</p> <pre><code>nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2022 NVIDIA Corporation Built on Wed_Jun__8_16:49:14_PDT_2022 Cuda compilation tools, release 11.7, V11.7.99 Build cuda_11.7.r11.7/compiler.31442593_0 ...
<p>tldr - &quot;installed cuda&quot; doesn't mean &quot;cuda can be used by the card.&quot;</p> <p>ultimately I had to get nvidia-smi work. the easiest way to do it was by using NVIDIA drivers that came with ubuntu.</p>
588
pytorch
PyTorch : predict single example
https://stackoverflow.com/questions/51041128/pytorch-predict-single-example
<p>Following the example from: </p> <p><a href="https://github.com/jcjohnson/pytorch-examples" rel="noreferrer">https://github.com/jcjohnson/pytorch-examples</a></p> <p>This code trains successfully: </p> <pre><code># Code in file tensor/two_layer_net_tensor.py import torch device = torch.device('cpu') # device = t...
<p>The code you posted is a simple demo trying to reveal the inner mechanism of such deep learning frameworks. These frameworks, including PyTorch, Keras, Tensorflow and many more automatically handle the forward calculation, the tracking and applying gradients for you as long as you defined the network structure. Howe...
589
pytorch
CUDA HOME in pytorch installation
https://stackoverflow.com/questions/52298146/cuda-home-in-pytorch-installation
<p>I installed pytorch via conda with cuda 7.5</p> <pre><code>conda install pytorch=0.3.0 cuda75 -c pytorch &gt;&gt;&gt; import torch &gt;&gt;&gt; torch.cuda.is_available() True </code></pre> <p>I didn't do any other installations for cuda other than this, since it looks like pytorch comes with cuda</p> <p>Now, I a...
<p>The CUDA package which is distributed via anaconda is not a complete CUDA toolkit installation. It only includes the necessary libraries and tools to support <code>numba</code> and <code>pyculib</code> and other GPU accelerated binary packages they distribute, like <code>tensorflow</code> and <code>pytorch</code>.</...
590
pytorch
pytorch PIP and CONDA error?
https://stackoverflow.com/questions/47943081/pytorch-pip-and-conda-error
<p>Guys I am new to python and deeplearning world</p> <p>I tried to install pytorch using conda</p> <p>I get this Error...</p> <pre><code>(base) C:\WINDOWS\system32&gt;conda install pytorch </code></pre> <blockquote> <p>`Solving environment: failed</p> </blockquote> <p>PackagesNotFoundError: The following packag...
<p>However I found how to use Pytorch on windows here: [<a href="https://www.superdatascience.com/pytorch/]" rel="nofollow noreferrer">https://www.superdatascience.com/pytorch/]</a></p> <p>conda install -c peterjc123 pytorch</p> <p>Did the trick for me ...</p>
591
pytorch
PyTorch not downloading
https://stackoverflow.com/questions/57642019/pytorch-not-downloading
<p>I go to the PyTorch website and select the following options</p> <p>PyTorch Build: Stable (1.2)</p> <p>Your OS: Windows</p> <p>Package: pip</p> <p>Language: Python 3.7</p> <p>CUDA: None</p> <p>(All of these are correct)</p> <p>Than it displays a command to run</p> <p><code>pip3 install torch==1.2.0+cpu torch...
<p>I've been in same situation. My prob was, the python version... I mean, in the 'bit' way.</p> <p>It was 32 bit that the python I'd installed. You should check which bit of python you installed. you can check in the app in setting, search python, then you will see the which bit you've installed.</p> <p>After I i...
592
pytorch
pytorch package too huge
https://stackoverflow.com/questions/69526212/pytorch-package-too-huge
<p>After installing pytorch via</p> <pre><code>RUN python3 -m pip install --no-cache-dir torch==1.9.1 </code></pre> <p>I realised that corresponding docker layer is 1.78GB Is there any way to reduce pytorch size? Current version is with GPU &amp; Cuda 10.2</p>
<p>If you are not using <strong>gpu</strong> with your docker container, the <strong>cpu</strong> version will be much smaller since it does not contain all the overhead of <strong>CUDA</strong>. To have a <strong>cpu</strong> only version you can use :</p> <pre><code>RUN python3 -m pip install --no-cache-dir torch==1....
593
pytorch
Tensorflow to PyTorch
https://stackoverflow.com/questions/65092587/tensorflow-to-pytorch
<p>I'm transffering a Tensorflow code to a PyTorch code.<br /> Below lines are the problem I couldn't solve yet.<br /> I'm not familiar with PyTorch so that it's not easy for me to find the matching methods in PyTorch library.<br /> Anyone can help me?<br /> p.s. The shape of alpha is (batch, N).</p> <pre><code>alpha_c...
<p>I've put all your functions followed by the corresponding pytorch function. Most are the same name and put in the pytorch docs (<a href="https://pytorch.org/docs/stable/index.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/index.html</a>)</p> <pre class="lang-py prettyprint-override"><code>tf.cumsum(...
594
pytorch
Get the data type of a PyTorch tensor
https://stackoverflow.com/questions/53374499/get-the-data-type-of-a-pytorch-tensor
<p>I understand that PyTorch tensors are homogenous, ie, each of the elements are of the same type.</p> <p>How do I find out the type of the elements in a PyTorch tensor?</p>
<p>There are three kinds of things:</p> <pre><code>dtype || CPU tensor || GPU tensor torch.float32 torch.FloatTensor torch.cuda.FloatTensor </code></pre> <p>The first one you get with <code>print(t.dtype)</code> if <code>t</code> is your tensor, else you use <co...
595
pytorch
Runtime Error when converting Pytorch model to PyTorch jit script
https://stackoverflow.com/questions/74907368/runtime-error-when-converting-pytorch-model-to-pytorch-jit-script
<p>I am trying to make a simple PyTorch model and convert it to PyTorch jit script using below code. (Final goal is to convert it to PyTorch Mobile)</p> <pre><code>class Concat(nn.Module): def __init__(self): super(Concat, self).__init__() def forward(self, x): return torch.cat(x,1) class Net(...
<p><strong>Why the error happens</strong></p> <p>While compiling <code>Concat.forward</code>, <code>torch.jit</code> assumes the parameter <code>x</code> is a <code>Tensor</code>. Later, <code>torch.jit</code> realizes the actual argument passed to <code>Concat.forward</code> is a tuple <code>(y, z)</code>, so <code>to...
596
pytorch
Pytorch installation
https://stackoverflow.com/questions/77478747/pytorch-installation
<p>I am trying to install Pytorch in python 3.12.0 and cuda 12.1 in windows 11 ? But I get the error</p> <p>ERROR: could not find a version that satisfies the requirement torch(from version: None) ERROR: No matching distribution found for torch</p> <p>I installed the nvidia cuda 12.1 as well</p> <p>I tried to install P...
<p>Now, pytorch 2.2.0, 2.2.1 and 2.2.2 support windows with cuda 12.1.</p> <p>By the way, I build a tool website for easy find and download right install wheels.</p> <p><a href="https://install.pytorch.site/?python=Python+3.12&amp;device=CUDA+12.1" rel="nofollow noreferrer">https://install.pytorch.site/?python=Python+3...
597
pytorch
Keras Upsampling2d vs PyTorch Upsampling
https://stackoverflow.com/questions/71585394/keras-upsampling2d-vs-pytorch-upsampling
<p>I am trying to convert a Keras Model to PyTorch. Now, it involves the <code>UpSampling2D</code> from <code>keras</code>. When I used <code>torch.nn.UpsamplingNearest2d</code> in pytorch, as default value of <code>UpSampling2D</code> in keras is <code>nearest</code>, I got different inconsistent results. The example ...
<p>In keras, it uses a scaling factor to upsample. <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/UpSampling2D" rel="nofollow noreferrer">SOURCE</a>.</p> <pre><code>tf.keras.layers.UpSampling2D(size, interpolation='nearest') </code></pre> <blockquote> <p>size: Int, or tuple of 2 integers. The upsam...
598
pytorch
PyTorch model input shape
https://stackoverflow.com/questions/66488807/pytorch-model-input-shape
<p>I loaded a custom PyTorch model and I want to find out its input shape. Something like this:</p> <pre><code>model.input_shape </code></pre> <p>Is it possible to get this information?</p> <hr /> <p><strong>Update:</strong> <code>print()</code> and <code>summary()</code> don't show this model's input shape, so they ar...
<h1>PyTorch flexibility</h1> <p>PyTorch models are very flexible objects, to the point where they do not enforce or generally expect a fixed input shape for data.</p> <p>If you have certain layers there may be constraints e.g:</p> <ul> <li>a flatten followed by a fully connected layer of width N would enforce the dimen...
599
pandas
How can I iterate over rows in a Pandas DataFrame?
https://stackoverflow.com/questions/16476924/how-can-i-iterate-over-rows-in-a-pandas-dataframe
<p>I have a pandas dataframe, <code>df</code>:</p> <pre class="lang-none prettyprint-override"><code> c1 c2 0 10 100 1 11 110 2 12 120 </code></pre> <p>How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example:</p> ...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows" rel="noreferrer"><code>DataFrame.iterrows</code></a> is a generator which yields both the index and row (as a Series):</p> <pre><code>import pandas as pd df = pd.DataFrame({'c1': [10, 11, 12...
600
pandas
How do I select rows from a DataFrame based on column values?
https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values
<p>How can I select rows from a DataFrame based on values in some column in Pandas?</p> <p>In SQL, I would use:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM table WHERE column_name = some_value </code></pre>
<p>To select rows whose column value equals a scalar, <code>some_value</code>, use <code>==</code>:</p> <pre><code>df.loc[df['column_name'] == some_value] </code></pre> <p>To select rows whose column value is in an iterable, <code>some_values</code>, use <code>isin</code>:</p> <pre><code>df.loc[df['column_name'].isin(s...
601
pandas
How do I change the size of figures drawn with Matplotlib?
https://stackoverflow.com/questions/332289/how-do-i-change-the-size-of-figures-drawn-with-matplotlib
<p>How do I change the size of figure drawn with Matplotlib?</p>
<p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html" rel="noreferrer"><code>figure</code></a> tells you the call signature:</p> <pre><code>from matplotlib.pyplot import figure figure(figsize=(8, 6), dpi=80) </code></pre> <p><code>figure(figsize=(1,1))</code> would create an inch-by-inch...
602
pandas
Renaming column names in Pandas
https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas
<p>I want to change the column labels of a Pandas DataFrame from</p> <pre><code>['$a', '$b', '$c', '$d', '$e'] </code></pre> <p>to</p> <pre><code>['a', 'b', 'c', 'd', 'e'] </code></pre>
<p>Just assign it to the <code>.columns</code> attribute:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'$a':[1,2], '$b': [10,20]}) &gt;&gt;&gt; df $a $b 0 1 10 1 2 20 &gt;&gt;&gt; df.columns = ['a', 'b'] &gt;&gt;&gt; df a b 0 1 10 1 2 20 </code></pre>
603
pandas
Delete a column from a Pandas DataFrame
https://stackoverflow.com/questions/13411544/delete-a-column-from-a-pandas-dataframe
<p>To delete a column in a DataFrame, I can successfully use:</p> <pre class="lang-py prettyprint-override"><code>del df['column_name'] </code></pre> <p>But why can't I use the following?</p> <pre class="lang-py prettyprint-override"><code>del df.column_name </code></pre> <p>Since it is possible to access the Series vi...
<p>As you've guessed, the right syntax is </p> <pre><code>del df['column_name'] </code></pre> <p>It's difficult to make <code>del df.column_name</code> work simply as the result of syntactic limitations in Python. <code>del df[name]</code> gets translated to <code>df.__delitem__(name)</code> under the covers by Pytho...
604
pandas
How do I get the row count of a Pandas DataFrame?
https://stackoverflow.com/questions/15943769/how-do-i-get-the-row-count-of-a-pandas-dataframe
<p>How do I get the number of rows of a pandas dataframe <code>df</code>?</p>
<p>For a dataframe <code>df</code>, one can use any of the following:</p> <ul> <li><code>len(df.index)</code></li> <li><code>df.shape[0]</code></li> <li><code>df[df.columns[0]].count()</code> (== <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.count.html" rel="noreferrer">number of non-NaN values</a...
605
pandas
Selecting multiple columns in a Pandas dataframe
https://stackoverflow.com/questions/11285613/selecting-multiple-columns-in-a-pandas-dataframe
<p>How do I select columns <code>a</code> and <code>b</code> from <code>df</code>, and save them into a new dataframe <code>df1</code>?</p> <pre class="lang-none prettyprint-override"><code>index a b c 1 2 3 4 2 3 4 5 </code></pre> <p>Unsuccessful attempt:</p> <pre class="lang-py prettyprint-over...
<p>The column names (which are strings) cannot be sliced in the manner you tried.</p> <p>Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the <a href="https://pandas.pydata.org/pandas-docs/stable/us...
606
pandas
How to change the order of DataFrame columns?
https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns
<p>I have the following DataFrame (<code>df</code>):</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) </code></pre> <p>I add more column(s) by assignment:</p> <pre class="lang-py prettyprint-override"><code>df['mean'] = df.mean(1) </code></pre> <p>How can I move the column...
<p>One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed. </p> <p>This is what you have now: </p> <pre><code>In [6]: df Out[6]: 0 1 2 3 4 mean 0 0.445598 0.173835 0.343415 0.682252 0.582616 0.445543 1 0.881592 0.696942 ...
607
pandas
Change column type in pandas
https://stackoverflow.com/questions/15891038/change-column-type-in-pandas
<p>I created a DataFrame from a list of lists:</p> <pre class="lang-py prettyprint-override"><code>table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ] df = pd.DataFrame(table) </code></pre> <p>How do I convert the columns to specific types? In this case, I want to convert co...
<p>You have four main options for converting types in pandas:</p> <ol> <li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric()</code></a> - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also <a ...
608
pandas
Create a Pandas Dataframe by appending one row at a time
https://stackoverflow.com/questions/10715965/create-a-pandas-dataframe-by-appending-one-row-at-a-time
<p>How do I create an empty <code>DataFrame</code>, then add rows, one by one?</p> <p>I created an empty <code>DataFrame</code>:</p> <pre><code>df = pd.DataFrame(columns=('lib', 'qty1', 'qty2')) </code></pre> <p>Then I can add a new row at the end and fill a single field with:</p> <pre><code>df = df._set_value(index=le...
<p>You can use <code>df.loc[i]</code>, where the row with index <code>i</code> will be what you specify it to be in the dataframe.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from numpy.random import randint &gt;&gt;&gt; df = pd.DataFrame(columns=['lib', 'qty1', 'qty2']) &gt;&gt;&gt; for i in range(5)...
609
pandas
Pretty-print an entire Pandas Series / DataFrame
https://stackoverflow.com/questions/19124601/pretty-print-an-entire-pandas-series-dataframe
<p>I work with Series and DataFrames on the terminal a lot. The default <code>__repr__</code> for a Series returns a reduced sample, with some head and tail values, but the rest missing.</p> <p>Is there a builtin way to pretty-print the entire Series / DataFrame? Ideally, it would support proper alignment, perhaps bo...
<p>You can also use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.option_context.html" rel="noreferrer"><code>option_context</code></a>, with one or more options:</p> <pre><code>with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified a...
610
pandas
How to deal with SettingWithCopyWarning in Pandas
https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas
<h2>Background</h2> <p>I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:</p> <pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataF...
<p>The <code>SettingWithCopyWarning</code> was created to flag potentially confusing &quot;chained&quot; assignments, such as the following, which does not always work as expected, particularly when the first selection returns a <em>copy</em>. [see <a href="https://github.com/pydata/pandas/pull/5390" rel="noreferrer">...
611
pandas
How to drop rows of Pandas DataFrame whose value in a certain column is NaN
https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan
<p>I have this DataFrame and want only the records whose EPS column is not NaN:</p> <pre class="lang-none prettyprint-override"><code> STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 2011...
<p>Don't drop, just take the rows where EPS is not NA:</p> <pre class="lang-py prettyprint-override"><code>df = df[df['EPS'].notna()] </code></pre>
612
pandas
How to add a new column to an existing DataFrame
https://stackoverflow.com/questions/12555323/how-to-add-a-new-column-to-an-existing-dataframe
<p>I have the following indexed DataFrame with named columns and rows not- continuous numbers:</p> <pre class="lang-none prettyprint-override"><code> a b c d 2 0.671399 0.101208 -0.181532 0.241273 3 0.446172 -0.243316 0.051767 1.577318 5 0.614758 0.075793 -0.451460 -0.012493 </c...
<p><strong>Edit 2017</strong></p> <p>As indicated in the comments and by @Alexander, currently the best method to add the values of a Series as a new column of a DataFrame could be using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="noreferrer"><strong><code>assi...
613
pandas
Get a list from Pandas DataFrame column headers
https://stackoverflow.com/questions/19482970/get-a-list-from-pandas-dataframe-column-headers
<p>I want to get a list of the column headers from a Pandas DataFrame. The DataFrame will come from user input, so I won't know how many columns there will be or what they will be called.</p> <p>For example, if I'm given a DataFrame like this:</p> <pre class="lang-none prettyprint-override"><code> y gdp cap 0 1...
<p>You can get the values as a list by doing:</p> <pre><code>list(my_dataframe.columns.values) </code></pre> <p>Also you can simply use (as shown in <a href="https://stackoverflow.com/a/19483602/4909087">Ed Chum's answer</a>):</p> <pre><code>list(my_dataframe) </code></pre>
614
pandas
Use a list of values to select rows from a Pandas dataframe
https://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe
<p>Let’s say I have the following Pandas dataframe:</p> <pre><code>df = DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]}) df A B 0 5 1 1 6 2 2 3 3 3 4 5 </code></pre> <p>I can subset based on a specific value:</p> <pre><code>x = df[df['A'] == 3] x A B 2 3 3 </code></pre> <p>But how ca...
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="noreferrer"><code>isin</code></a> method:</p> <pre><code>In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]}) In [2]: df Out[2]: A B 0 5 1 1 6 2 2 3 3 3 4 5 In [3]: df[df['A'].isin([...
615
pandas
Convert list of dictionaries to a pandas DataFrame
https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe
<p>How can I convert a list of dictionaries into a DataFrame? I want to turn</p> <pre class="lang-py prettyprint-override"><code>[{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': &quot;february&quot;}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month'...
<p>If <code>ds</code> is a list of <code>dict</code>s:</p> <pre><code>df = pd.DataFrame(ds) </code></pre> <p>Note: this does not work with nested data.</p>
616
pandas
&quot;Large data&quot; workflows using pandas
https://stackoverflow.com/questions/14262433/large-data-workflows-using-pandas
<p>I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.</p> <p>One day I hope to replace my use of SAS with python and pan...
<p>I routinely use tens of gigabytes of data in just this fashion e.g. I have tables on disk that I read via queries, create data and append back.</p> <p>It's worth reading <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#hdf5-pytables" rel="noreferrer">the docs</a> and <a href="https://groups.google.c...
617
pandas
Writing a pandas DataFrame to CSV file
https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file
<p>I have a dataframe in pandas which I would like to write to a CSV file.</p> <p>I am doing this using:</p> <pre class="lang-py prettyprint-override"><code>df.to_csv('out.csv') </code></pre> <p>And getting the following error:</p> <pre class="lang-none prettyprint-override"><code>UnicodeEncodeError: 'ascii' codec can'...
<p>To delimit by a tab you can use the <code>sep</code> argument of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="noreferrer"><code>to_csv</code></a>:</p> <pre><code>df.to_csv(file_name, sep='\t') </code></pre> <p>To use a specific encoding (e.g. 'utf-8') use the <cod...
618
pandas
How do I expand the output display to see more columns of a Pandas DataFrame?
https://stackoverflow.com/questions/11707586/how-do-i-expand-the-output-display-to-see-more-columns-of-a-pandas-dataframe
<p>Is there a way to widen the display of output in either interactive or script-execution mode?</p> <p>Specifically, I am using the <code>describe()</code> function on a Pandas <code>DataFrame</code>. When the <code>DataFrame</code> is five columns (labels) wide, I get the descriptive statistics that I want. However...
<p>(For Pandas versions before 0.23.4, see at bottom.)</p> <p>Use <code>pandas.set_option(optname, val)</code>, or equivalently <code>pd.options.&lt;opt.hierarchical.name&gt; = val</code>. Like:</p> <pre><code>import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_o...
619
pandas
Creating an empty Pandas DataFrame, and then filling it
https://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-and-then-filling-it
<p>I'm starting from the pandas DataFrame documentation here: <em><a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html" rel="noreferrer">Introduction to data structures</a></em></p> <p>I'd like to iteratively fill the DataFrame with values in a time series kind of calculation. I'd like to initialize the Da...
<p>Here's a couple of suggestions:</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="noreferrer"><code>date_range</code></a> for the index:</p> <pre><code>import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd....
620
pandas
Deleting DataFrame row in Pandas based on column value
https://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value
<p>I have the following DataFrame:</p> <pre class="lang-none prettyprint-override"><code> daysago line_race rating rw wrating line_date 2007-03-31 62 11 56 1.000000 56.000000 2007-03-10 83 11 67 1.000000 67....
<p>If I'm understanding correctly, it should be as simple as:</p> <pre><code>df = df[df.line_race != 0] </code></pre>
621
pandas
Combine two columns of text in pandas dataframe
https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-pandas-dataframe
<p>I have a dataframe that looks like</p> <pre class="lang-none prettyprint-override"><code>Year quarter 2000 q2 2001 q3 </code></pre> <p>How do I add a new column by combining these columns to get the following dataframe?</p> <pre class="lang-none prettyprint-override"><code>Year quarter period 2000 ...
<p>If both columns are strings, you can concatenate them directly:</p> <pre><code>df[&quot;period&quot;] = df[&quot;Year&quot;] + df[&quot;quarter&quot;] </code></pre> <p>If one (or both) of the columns are not string typed, you should convert it (them) first,</p> <pre><code>df[&quot;period&quot;] = df[&quot;Year&quot;...
622
pandas
How are iloc and loc different?
https://stackoverflow.com/questions/31593201/how-are-iloc-and-loc-different
<p>Can someone explain how these two methods of slicing are different? I've seen <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="noreferrer">the docs</a> and I've seen previous similar questions (<a href="https://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat">1...
<h2>Label <em>vs.</em> Location</h2> <p>The main distinction between the two methods is:</p> <ul> <li><p><code>loc</code> gets rows (and/or columns) with particular <strong>labels</strong>.</p> </li> <li><p><code>iloc</code> gets rows (and/or columns) at integer <strong>locations</strong>.</p> </li> </ul> <p>To demonst...
623
pandas
How do I count the NaN values in a column in pandas DataFrame?
https://stackoverflow.com/questions/26266362/how-do-i-count-the-nan-values-in-a-column-in-pandas-dataframe
<p>I want to find the number of <code>NaN</code> in each column of my data.</p>
<p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.isna.html" rel="noreferrer"><code>isna()</code></a> method (or it's alias <code>isnull()</code> which is also compatible with older pandas versions &lt; 0.21.0) and then sum to count the NaN values. For one column:</p> <pre><code>&gt;&gt;...
624
pandas
How to delete rows from a pandas DataFrame based on a conditional expression
https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression
<p>I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2.</p> <p>I expect to be able to do this (per <a href="https://stackoverflow.com/questions/11881165/slice-pandas-dataframe-by-row">this answer</a>):</p> <pre><code>df[(len(df['column na...
<p>When you do <code>len(df['column name'])</code> you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply <code>len</code> to each element in the column, use <code>df['column name'].map(len)</code>. So try</p> <pre><code>df[df['column...
625
pandas
Pandas Merging 101
https://stackoverflow.com/questions/53645882/pandas-merging-101
<ul> <li>How can I perform a (<code>INNER</code>| (<code>LEFT</code>|<code>RIGHT</code>|<code>FULL</code>) <code>OUTER</code>) <code>JOIN</code> with pandas?</li> <li>How do I add NaNs for missing rows after a merge?</li> <li>How do I get rid of NaNs after merging?</li> <li>Can I merge on the index?</li> <li>How do I m...
<p>This post aims to give readers a primer on SQL-flavored merging with Pandas, how to use it, and when not to use it.</p> <p>In particular, here's what this post will go through:</p> <ul> <li><p>The basics - types of joins (LEFT, RIGHT, OUTER, INNER)</p> <ul> <li>merging with different column names</li> <li>merging wi...
626
pandas
Filter pandas DataFrame by substring criteria
https://stackoverflow.com/questions/11350770/filter-pandas-dataframe-by-substring-criteria
<p>I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.</p> <p>Something like this idiom:</p> <pre class="lang-py prettyprint-override"><code>re.search(pattern, cell_in_question) </code></pre> <p>returning a boolean. I am familiar with the syntax of <code>df[...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#string-methods" rel="noreferrer">Vectorized string methods (i.e. <code>Series.str</code>)</a> let you do the following:</p> <pre><code>df[df['A'].str.contains(&quot;hello&quot;)] </code></pre> <p>This is available in pandas <a href="https://p...
627
pandas
How to filter Pandas dataframe using &#39;in&#39; and &#39;not in&#39; like in SQL
https://stackoverflow.com/questions/19960077/how-to-filter-pandas-dataframe-using-in-and-not-in-like-in-sql
<p>How can I achieve the equivalents of SQL's <code>IN</code> and <code>NOT IN</code>?</p> <p>I have a list with the required values. Here's the scenario:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']}) countries_to_keep = ['UK', 'China'] # pseudo-co...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="noreferrer"><code>pd.Series.isin</code></a>.</p> <p>For &quot;IN&quot; use: <code>something.isin(somewhere)</code></p> <p>Or for &quot;NOT IN&quot;: <code>~something.isin(somewhere)</code></p> <p>As a worked exa...
628
pandas
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o
<p>I want to filter my dataframe with an <code>or</code> condition to keep rows with a particular column's values that are outside the range <code>[-0.25, 0.25]</code>. I tried:</p> <pre><code>df = df[(df['col'] &lt; -0.25) or (df['col'] &gt; 0.25)] </code></pre> <p>But I get the error:</p> <blockquote> <p>ValueError: ...
<p>The <code>or</code> and <code>and</code> Python statements require <strong>truth</strong>-values. For pandas, these are considered ambiguous, so you should use &quot;bitwise&quot; <code>|</code> (or) or <code>&amp;</code> (and) operations:</p> <pre><code>df = df[(df['col'] &lt; -0.25) | (df['col'] &gt; 0.25)] </code...
629
pandas
Shuffle DataFrame rows
https://stackoverflow.com/questions/29576430/shuffle-dataframe-rows
<p>I have the following DataFrame:</p> <pre><code> Col1 Col2 Col3 Type 0 1 2 3 1 1 4 5 6 1 ... 20 7 8 9 2 21 10 11 12 2 ... 45 13 14 15 3 46 16 17 18 3 ... </code></pre> <p>The DataFrame is read from a CSV file. All rows whic...
<p>The idiomatic way to do this with Pandas is to use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="noreferrer"><code>.sample</code></a> method of your data frame to sample all rows without replacement:</p> <pre class="lang-py prettyprint-override"><code>df.s...
630
pandas
pandas.parser.CParserError: Error tokenizing data
https://stackoverflow.com/questions/18039057/pandas-parser-cparsererror-error-tokenizing-data
<p>I'm trying to use pandas to manipulate a .csv file but I get this error:</p> <blockquote> <p>pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12</p> </blockquote> <p>I have tried to read the pandas docs, but found nothing.</p> <p>My code is simple:</p> <pre><code>path = '...
<p>you could also try;</p> <pre><code>data = pd.read_csv('file1.csv', on_bad_lines='skip') </code></pre> <p>Do note that this will cause the offending lines to be skipped. If you don't expect many bad lines and want to (at least) know their amount and IDs, use <code>on_bad_lines='warn'</code>. For advanced handling of ...
631
pandas
Constructing DataFrame from values in variables yields &quot;ValueError: If using all scalar values, you must pass an index&quot;
https://stackoverflow.com/questions/17839973/constructing-dataframe-from-values-in-variables-yields-valueerror-if-using-all
<p>I have two variables as follows.</p> <pre class="lang-py prettyprint-override"><code>a = 2 b = 3 </code></pre> <p>I want to construct a DataFrame from this:</p> <pre class="lang-py prettyprint-override"><code>df2 = pd.DataFrame({'A':a, 'B':b}) </code></pre> <p>This generates an error:</p> <pre class="lang-none prett...
<p>The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'A': [a], 'B': [b]}) &gt;&gt;&gt; df A B 0 2 3 </code></pre> <p>or use scalar values and pass an in...
632
pandas
How to convert index of a pandas dataframe into a column
https://stackoverflow.com/questions/20461165/how-to-convert-index-of-a-pandas-dataframe-into-a-column
<p>How to convert an index of a dataframe into a column?</p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code> gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 </code></pre> <p>to</p> <pre class="lang-none prettyprint-override"><code> index1 gi...
<p>either:</p> <pre><code>df['index1'] = df.index </code></pre> <p>or <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>.reset_index</code></a>:</p> <pre><code>df = df.reset_index() </code></pre> <hr /> <p>If you have a multi-index frame with 3 lev...
633