After installing RPy2 from
http://rpy.sourceforge.net/rpy2.html
I'm trying to use it in Python 2.6 IDLE but I'm getting this error:
>>> import rpy2.robjects as robjects
>>> robjects.r['pi']
<RVector - Python:0x0121D8F0 / R:0x022A1760>
What I'm doing wrong?
Have you tried looking at the vector that's returned?
>>> pi = robjects.r['pi']
>>> pi[0]
3.14159265358979
To expand on Shane's answer. rpy2 uses the following Python objects to represent the basic R types:
RVector: R scalars and vectors, R Lists are represented as RVectors with names, see below
RArray: an R matrix, essentially the RVector with a dimension
RDataFrame: an R data.frame
To coerce back to basic Python types look here.
As an example, I use this to convert an R List to a python dict:
rList = ro.r('''list(name1=1,name2=c(1,2,3))''')
pyDict = {}
for name,value in zip([i for i in rList.getnames()],[i for i in rList]):
if len(value) == 1: pyDict[name] = value[0]
else: pyDict[name] = [i for i in value]
In the Python interactive interpreter if an expression returns a value then that value is automatically printed. For example if you create a dictionary and extract a value from it the value is automatically printed, but if this was in an executing script this would not be the case. Look at the following simple example this is not an error but simply python printing the result of the expression:
>>> mymap = {"a":23}
>>> mymap["a"]
23
The same code in a python script would produce no output at all.
In your code you are accessing a map like structure with the code:
>>> robjects.r['pi']
This is returning some R2Py object for which the default string representation is: <RVector - Python:0x0121D8F0 / R:0x022A1760>
If you changed the code to something like:
pi = robjects.r['pi']
you would see no output but the result of the call (a vector) will be assigned to the variable pi and be available for you to use.
Looking at the R2Py documentation It seems many of the objects are by default printed as a type in <> brackets and some memory address information.
This is not an error, it's simply the 'repr' of the returned robject:
>>> r['pi']
<RVector - Python:0x2c14bd8 / R:0x3719538>
>>> repr(r['pi'])
'<RVector - Python:0x4b77908 / R:0x3719538>'
>>> str(r['pi'])
'[1] 3.141593'
>>> print r['pi']
[1] 3.141593
You can get the value of 'pi' accessing it by index
>>> r['pi'][0]
3.1415926535897931
To access element of named lists (the 'object$attribute' R syntax) I use
>>> l = r.list(a=r.c(1,2,3), b=r.c(4,5,6))
>>> print l
$a
[1] 1 2 3
$b
[1] 4 5 6
>>> print dict(zip(l.names, l))['a']
[1] 1 2 3
but I think there must be a better solution...
I found this as the only sensible, short discussion of how to go back and forth from R objects and python. naufraghi's solution prompted the following approach to converting a data.frame, which retains the nicer slicing capabilities of the dataframe:
In [69]: import numpy as np
In [70]: import rpy2.robjects as ro
In [71]: df = ro.r['data.frame'](a=r.c(1,2,3), b=r.c(4.0,5.0,6.3))
In [72]: df
Out[72]: <RDataFrame - Python:0x5492200 / R:0x4d00a28>
In [73]: print(df)
a b
1 1 4.0
2 2 5.0
3 3 6.3
In [74]: recdf = np.rec.fromarrays(df, names=tuple(df.names))
In [75]: recdf
Out[75]:
rec.array([(1, 4.0), (2, 5.0), (3, 6.2999999999999998)],
dtype=[('a', '<i4'), ('b', '<f8')])
Seems a bit off-topic at this point, but I'm not sure what the appropriate procedure would be to capture this question & answer of mine!
Related
I use asterisk notation in regular python as:
>>> x=(10,11)
>>> y=(12,13)
>>> z=99
>>> print(*x)
10 11
>>> print(*x, *y, z)
10 11 12 13 99
But when I try to do similar in python mode of Processing, it gives me essentially a syntax error: processing.app.SketchException: Maybe there's an unclosed paren or quote mark somewhere before this line?
p1= (20,20)
p2=(40,40)
c1 = (15,15)
c2 = (50,50)
print(p1)
print(*p1)
# bezier(**p1, **c1, **c2, **p2)
Is this not supported in Processing.PY?
It works fine, I use it all the time.
p1 = (20, 20)
p2 = (40, 40)
translate(*p1) # this works
# you can't use "star" unpacking twice like this.
# line(*p1, *p2) # this won't work!
Beware that in Python 2 print is not a function, so I have used from __future__ import print_function to make your example work on the image bellow. The print function can handle an arbitrary number of positional arguments, but again, not * "star" unpacking twice.
I have noticed in your question example ** which can be used for
keyword arguments & dictionary unpacking. It also works fine overall, but it would not work with the bezier() comment you provided. The error message might have misled you.
I am using the answer provided here to convert string IP to integer. But I am not getting expected output. Specifically, the method is
>>> ipstr = '1.2.3.4'
>>> parts = ipstr.split('.')
>>> (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3])
but when I provide it the value 172.31.22.98 I get 2887718498 back. However, I expect to see value -1407248798 as provided by Google's Guava library https://google.github.io/guava/releases/20.0/api/docs/com/google/common/net/InetAddresses.html#fromInteger-int-
Also, I've verified that this service provides expected output but all of the answers provided by the aforementioned StackOverflow answer return 2887718498
Note that I cannot use any third party library. So I am pretty much limited to using a hand-written code (no imports)
A better way is to use the library method
>>> from socket import inet_aton
>>> int.from_bytes(inet_aton('172.31.22.98'), byteorder="big")
2887718498
This is still the same result you had above
Here is one way to view it as a signed int
>>> from ctypes import c_long
>>> c_long(2887718498)
c_long(-1407248798)
To do it without imports (but why? The above is all first party CPython)
>>> x = 2887718498
>>> if x >= (1<<31): x-= (1<<32)
>>> x
-1407248798
Found this post whilst trying to do the same as OP. Developed the below for my simple mind to understand and for someone to benefit from.
baseIP = '192.168.1.0'
baseIPFirstOctet = (int((baseIP).split('.')[0]))
baseIPSecondOctet = (int((baseIP).split('.')[1]))
baseIPThirdOctet = (int((baseIP).split('.')[2]))
baseIPFourthOctet = (int((baseIP).split('.')[3]))
I am trying to convert the following code from c to Python. The C code looks like:
seed = (time(0) ^ (getpid() << 16));
fprintf("0x%08x \n", seed);
that outputs values like 0x7d24defb.
And the python code:
time1 = int(time.time())
seed = (time1 ^ (os.getpid() <<16))
that outputs values like: 1492460964
What do i need to modify at the python code so I get address-like values?
It depends on the way the value is displayed. The %x flag in printf-functions displays the given value in hexadecimal. In Python you can use the hex function to convert the value to a hexadecimal representation.
The equivalent Python code to: fprintf("0x%08x \n", seed);
>>> '0x{:08x}"'.format(1492460964)
'0x58f525a4"'
Note that hex() alone won't pad zeros to size 8 like the C code does.
I suppose this is what you what:
>>> n =hex (int(time.time()) ^ (os.getpid() <<16))
>>> print n
0x431c2fd2
>>>
I need to save a tuple of 4 numbers inside a column that only accepts numbers (int or floats)
I have a list of 4 number like -0.0123445552, -29394.2393339, 0.299393333, 0.00002345556.
How can I "store" all these numbers inside a number and be able to retrieve the original tuple in Python?
Thanks
Following up on #YevgenYampolskiy's idea of using numpy:
You could use numpy to convert the numbers to 16-bit floats, and then view the array as one 64-bit int:
import numpy as np
data = np.array((-0.0123445552, -29394.2393339, 0.299393333, 0.00002345556))
stored_int = data.astype('float16').view('int64')[0]
print(stored_int)
# 110959187158999634
recovered = np.array([stored_int], dtype='int64').view('float16')
print(recovered)
# [ -1.23443604e-02 -2.93920000e+04 2.99316406e-01 2.34842300e-05]
Note: This requires numpy version 1.6 or better, as this was the first version to support 16-bit floats.
If by int you mean the datatype int in Python (which is unlimited as of the current version), you may use the following solution
>>> x
(-0.0123445552, -29394.2393339, 0.299393333, 2.345556e-05)
>>> def encode(data):
sz_data = str(data)
import base64
b64_data = base64.b16encode(sz_data)
int_data = int(b64_data, 16)
return int_data
>>> encode(x)
7475673073900173755504583442986834619410853148159171975880377161427327210207077083318036472388282266880288275998775936614297529315947984169L
>>> def decode(data):
int_data = data
import base64
hex_data = hex(int_data)[2:].upper()
if hex_data[-1] == 'L':
hex_data = hex_data[:-1]
b64_data = base64.b16decode(hex_data)
import ast
sz_data = ast.literal_eval(b64_data)
return sz_data
>>> decode(encode(x))
(-0.0123445552, -29394.2393339, 0.299393333, 2.345556e-05)
You can combine 4 integers into a single integer, or two floats into a double using struct module:
from struct import *
s = pack('hhhh', 1, -2, 3,-4)
i = unpack('Q', pack('Q', i[0]))
print i
print unpack('hhhh', s)
s = pack('ff', 1.12, -2.32)
f = unpack('d', s)
print f
print unpack('ff', pack('d', f[0]))
prints
(18445618190982447105L,)
(1, -2, 3, -4)
(-5.119999879002571,)
(1.1200000047683716, -2.319999933242798)
Basically in this example tuple (1,-2,3,-4) gets packed into an integer 18445618190982447105, and tuple ( 1.12, -2.32) gets packed into -5.119999879002571
To pack 4 floats into a single float you will need to use half-floats, however this is a problem here:
With half-float it looks like there is no native support in python as of now:
http://bugs.python.org/issue11734
However numpy module do have some support for half-floats (http://docs.scipy.org/doc/numpy/user/basics.types.html). Maybe you can use it somehow to pack 4 floats into a single float
This does not really answer your question, but what you're trying to do violates 1NF. Is changing the DB schema to introduce an intersection table really not an option?
my idea is weird; but will it work??
In [31]: nk="-0.0123445552, -29394.2393339, 0.299393333, 0.00002345556"
In [32]: nk1="".join(str(ord(x)) for x in nk)
In [33]: nk1
Out[33]: '454846484950515252535353504432455057515752465051575151515744324846505757515751515151443248464848484850515253535354'
In [34]: import math
In [35]: math.log(long(nk1), 1000)
Out[36]: 37.885954947611985
In [37]: math.pow(1000,_)
Out[37]: 4.548464849505043e+113
you can easily unpack this string(Out[33]); for example split it at 32; its for space.
also this string is very long; we can make it to a small number by math.log; as we got in Out[36].
Following this question which asks (and answers) how to read .mat files that were created in Matlab using Scipy, I want to know how to access the fields in the imported structs.
I have a file in Matlab from which I can import a struct:
>> load bla % imports a struct called G
>> G
G =
Inp: [40x40x2016 uint8]
Tgt: [8x2016 double]
Ltr: [1x2016 double]
Relevant: [1 2 3 4 5 6 7 8]
Now I want to do the same in Python:
x = scipy.io.loadmat('bla.mat')
>>> x
{'__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Wed Jun 07 21:17:24 2006', 'G': array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object), '__globals__': []}
>>> x['G']
array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object)
>>> G = x['G']
>>> G
array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object)
The question is, how can I access the members of the struct G: Inp, Tgt, Ltr and Relevant, the way I can in Matlab?
First, I'd recommend to upgrade to Scipy svn if possible - there has been active development of the matlab io with some really dramatic speed ups recently.
Also as mentioned it might be worth trying with struct_as_record=True. But otherwise you should be able to get it out by playing around interactively.
Your G is an array of mio struct objects - you can check G.shape for example. In this case I think G = x['G'][0,0] should give the object you want. Then you should be able to access G.Inp etc.