knitr - error when importing python module
Asked Answered
L

2

13

I am having trouble when running the 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 get the 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

It must be something to do with system path and where I am pointing.

Normally in IPython i use

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

To add paths. I don't know what the problem is.

Libau answered 11/5, 2015 at 16:30 Comment(4)
Are you trying to use sys with knitr as well?Reprehend
So I first tried to use sys with knitr and it didn't work like it would work with IPython so then I tried something more simple like importing pandas and that didn't work. But I was able to import other packages e.g. numpy... Any idea why?Libau
Are the sources for your packages in different places? You could use the R equivalents, take a look at Sys.getenv("path").Reprehend
Can you post a hierarchical description of your packages?Paraprofessional
P
3

Use:

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

change C:/anaconda/python.exe to your python path.

Prussia answered 28/7, 2018 at 11:58 Comment(0)
T
1

This happened to me too, in Atom.

Check to make sure the two files are in the same directory. Put them in the same folder or path.

Then, go into Terminal or Command Line and type

cd Downloads

(or whatever large directory the files are in). Then, type in smaller folder like: cd _____, such as cd animals. There, you can open the one file that you want to have the other file import to by typing python3 -i ____.py (file name). Make sure the file has from ___(master file) import * and you can run the code in terminal.

This should work. The problem is you can't import by running the code. Instead, you have to link the two using terminal or command line.

Toffic answered 2/8, 2018 at 19:13 Comment(1)
Yup, got that. Thanks! ;)Toffic

© 2022 - 2024 — McMap. All rights reserved.