Knitr - error while importing python module

I am having problems running python engine in knitr. I can import some modules, but not others. For example, I can import numpy, but not pandas.

{r, engine='python'} import pandas

I am getting an error.

Quitting from lines 50-51 (prepayment.Rmd) 
Error in (knit_engines$get(options$engine))(options) : 
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named pandas
Calls: <Anonymous> ... process_group.block -> call_block -> block_exec -> in_dir -> <Anonymous>
In addition: Warning message:
running command ''python'  -c 'import pandas' 2>&1' had status 1 
Execution halted

      

This should be something to do with the system path and where I specify.

Usually in IPython I use

import sys
sys.path.append('/path/to/directory/')

      

Adding paths. I do not know what's the problem.

+13


source to share


3 answers


Using:

{python engine.path="C:/anaconda/python.exe"}
import pandas

      



change C: /anaconda/python.exe

to your path to python

.

+3


source


For some reason, it is slightly different from IPython

The following worked for me.

I first switched to IPython and did the following

import pandas
import os
path = os.path.dirname(pandas.__file__)
Out[4]: '/Users/glendonthompson/anaconda/lib/python2.7/site-packages/pandas'

      

Then in Rstudio in the .Rmd file I ran



```{r, engine='python'}
import sys
sys.path.append('/Users/glendonthompson/anaconda/lib/python2.7/site-packages/')
import pandas
```

      

Maybe it has something to do with anaconda, messing with my packages ....

Is this also true with knitr using the python engine you have to cache otherwise it won't save the code in the previous chunks?

```{r, engine='python'}
import sys
sys.path.append('/Users/glendonthompson/anaconda/lib/python2.7/site-packages/')
```

```{r,engine = 'python'}
import pandas
```

      

Does not work.

0


source


It happened to me too, in Atom.

Make sure both files are in the same directory. Place them in the same folder or path.

Then go to Terminal or Command Line and type

cd Downloads

(or whatever large directory the files are in). Then enter a smaller folder like: cd _____

eg cd animals

. There, you can open one file to which you want to import another file by typing python3 -i ____.py

(filename). Make sure the file has from ___(master file) import *

and you can run the code in the terminal.

This should work. The problem is that you cannot import by running the code. Instead, you need to link the two terminals using a terminal or command line.

0


source







All Articles