Note that there are some explanatory texts on larger screens.

plurals
  1. POJava type conversion to Python through JPype and numpy
    text
    copied!<p>I'm currently porting a program written in Python to Java and have run into some problems. I'm porting a part of the program at the time and for testing purposes I'm using JPype to make it compatible with the new java classes.</p> <p>EDIT: Just to makes things more clear, the class I'm currently working on provides data to the rest of the Python program.</p> <p>So, in my java class I have some float and byte values in ArrayLists,</p> <pre><code> ArrayList&lt;ArrayList&lt;Float&gt;&gt; dataFloat = new ArrayList&lt;ArrayList&lt;Float&gt;&gt;(); ArrayList&lt;ArrayList&lt;Byte&gt;&gt; dataByte = new ArrayList&lt;ArrayList&lt;Byte&gt;&gt;(); </code></pre> <p>Then with the use of JPype I am able to get these into my Python environment which now has the type</p> <pre><code> &lt;class 'jpype._jclass.java.util.ArrayList'&gt; . </code></pre> <p>Now I wanted to simply convert these to numpy arrays in Python, </p> <pre><code> numpy.array(dataFloat) . </code></pre> <p>Which seemed to work at first as it looked nice when it was printed out,</p> <pre><code> [[1.0 2.0 3.0] [80.0 127.0 127.0] [255.0 255.0 255.0]] . </code></pre> <p>However, it did not work with the rest of the program because it demands that the values are of the type float. Looking further into the problem I found that these "float" values that I have are in fact</p> <pre><code> &lt;class 'jpype._jclass.java.lang.Float'&gt; </code></pre> <p>and not the regular Python float that I wanted. Compared to a regular numpy float array,</p> <pre><code>&gt;&gt;&gt; b = array([[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]) &gt;&gt;&gt; type((b[0])[0]) &lt;type 'numpy.float64'&gt; </code></pre> <p>which has the desired float type.</p> <p>To be able to run it with the rest of the Python program I had to convert the array per element with the java Float.floatValue(),</p> <pre><code> arr = numpy.array(dataFloat) a = array([]) for j in range(len(arr)): b = array([]) if array_equal(a,[]): for i in arr.get(j): a = append(a, i.floatValue()) else: for i in arr.get(j): b = append(b, i.floatValue()) a = vstack((a, b)) </code></pre> <p>And this of course takes a lot of time, especially when there are thousands of elements. </p> <p>Does anyone know this can be done in an efficient way? Simply put, I get a lot java.lang.Float values from JPype that need to be converted to regular Python float values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload