Passing python objects to R functions in rpy2 - python

I'm working in a Jupyter notebook with Python 2 and want to use rpy2 to plot a heatmap.
import numpy as np
from rpy2 import robjects
from rpy2.robjects import r, pandas2ri
from rpy2.robjects import Formula, Environment
from rpy2.robjects.vectors import IntVector, FloatVector
from rpy2.robjects.lib import grid
from rpy2.robjects.packages import importr, data
from rpy2.rinterface import RRuntimeError
import warnings
a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])
r.image.plot(a,b,c)
gives me the error
AttributeError: 'SignatureTranslatedFunction' object has no attribute 'plot'
How do I properly pass the parameters into this function? Specs: rpy2 2.5.6 with R3.3.3 and Python 2.7

That doesn't work because image.plot apparently comes from the package fields. Using image from base R's graphics library, do e.g. this:
import numpy as np
from rpy2.robjects.packages import importr
from rpy2.rinterface import RRuntimeError
import rpy2.robjects.numpy2ri
from IPython.display import Image, display
from rpy2.robjects.lib import grdevices
rpy2.robjects.numpy2ri.activate()
grf = importr('graphics')
a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])
with grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
grf.image(a, b, c)
display(Image(data=img.getvalue(), format='png', embed=True))
gives
To use image.plot, you'd have to run
fields = importr('fields')
and replace grf.image(a, b, c) with fields.image.plot(a, b, c)

Related

Issues importing some R packages to python

I want to import SCI package from R to Python
So i did this code:
Source: How to import r-packages in Python
# Using R inside python
import rpy2
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.packages import importr
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
# Install packages
packnames = ('SCI')
utils.install_packages(StrVector(packnames))
# Load packages
sci = importr('SCI')
But when i run:
utils = rpackages.importr('utils')
i get this error:
NotImplementedError: Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>'
and when i run :
utils.chooseCRANmirror(ind=1)
i get this:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'int'>'
How can i import this package to Python?
Thanks in advance.

Jupyter imported module not using library

I made an external module model.py and I want to import it within my Jupyter notebook.
# model.py
import numpy as np
import pandas as pd
from scipy.stats import chi2
from sklearn.covariance import EllipticEnvelope
from sklearn.base import BaseEstimator
from scipy.stats import combine_pvalues
# ...
def predict(self, xtest):
return np.where(self.predict_proba(xtest, False) < self.critical_value, 1., -1.)
When I try to call the predict method of my model class I get the error:
NameError: name 'np' is not defined.
I have the numpy library installed and I am strugggling to understand why it is not able to use it.
Any ideas?

Downloading fundamental data from Yahoo Finance

I'm trying to download fundamental data from Yahoo Finance like PE ratios, PB ratios, EV/EBITDA, etc. This is what I've done so far:
#import required libraries
import pandas as pd
import numpy as np
import requests
import xlsxwriter
from scipy import stats
import math
import secrets
import yfinance as yf
import matplotlib.pyplot as plt
import datetime as dt
import statsmodels.api as sm
pip install requests_html
stocks = pd.read_csv('constituents.csv')
from yahoo_fin.stock_info import get_data
sm.get_stats_valuation("aapl")
I get this error:
AttributeError Traceback (most recent call last)
<ipython-input-17-7a641ee9069d> in <module>
----> 1 sm.get_stats_valuation("aapl")
AttributeError: module 'statsmodels.api' has no attribute 'get_stats_valuation'
What do I do?
I checked the website you specified in comment. I think you can get stats valuation from stock_info module itself of the yahoo_fin package. Please check:
import yahoo_fin.stock_info as si
si.get_stats_valuation("aapl")

Python not recognizing sub module in Jupyter

I have a problem using python module in Jupyter. It was working fine until yesterday. The only new thing is that I updated Seaborn to th elatest version. I do not have the pb when I use Spyder directly.
For exemple, I have a file that would be like :
import numpy as np
import pandas as pd
import scipy
def test_skewn(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
I work perfectly from Spyder but from Jupyter it return :
AttributeError: module 'scipy' has no attribute 'stats'
If I correct it like this :
import numpy as np
import pandas as pd
#import scipy
from scipy.stats import skew, kurtosis
def test_skewness(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
#current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
current_skew = skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
It works in Jupyter.
It was working with both version before and I am not confortable at all with this pb and I would like to understand where it can come from.

Print version of a module without importing the entire package

Is it possible to check the version of a package if only a module is imported?
When a package is imported like...
import pandas as pd
I use:
print('pandas : version {}'.format(pd.__version__))
to print the version number.
How do I check the version number if only a module is imported, like
import matplotlib.pyplot as plt
or
from sklearn.metrics import confusion_matrix
Any suggestions?
I usually do this:
import matplotlib.pyplot as plt
import sys
print (sys.modules[plt.__package__].__version__)
if you import just a function:
from sklearn.metrics import confusion_matrix as function
import sys
try:module_name = function.__module__[:function.__module__.index(".")]
except:module_name = function.__module__
print (sys.modules[module_name].__version__)
and if this doesn't work you could just import pip and for loop all the modules.

Categories