سؤال

I am trying to remove everything in the following array except for the two numbers and the , in between.

This is the array: [array([[ 1948.97753906, 1058.23937988]], dtype=float32)]

This array is always changing in size (can have 1 pair of numbers or 6 pairs etc) and being filled with different numbers, however, the format always remains the same.

I currently have the below code, however, I think this is only working when there is one pair of numbers in the array??

final = str(self.lostfeatures).strip('[array([[ ').strip(']], dtype=float32)')

Any help would be greatly appreciated!

هل كانت مفيدة؟

المحلول

if that is really just a prefix/suffix, use replace:

final = str(self.lostfeatures).replace('[array([[','').replace(']], dtype=float32)', '')

You can do something similar with regex:

numbers = re.findall('(?P<number>\d+\.\d+)', str(self.lostfeatures))

which will also give you an array of the numbers themselves (so it's trivial to cast to float from there).

However... if you are doing str(lostfeatures), the original must already be in an array. Why are you even casting to string? You should be able to extract the numerical array directly like this:

lostfeatures[0][0]

(you appear to have two levels of indirection... lostfeatures[0] = array([[ 1948.97753906, 1058.23937988]], then lostfeatures[0][0] == [1948.97753906, 1058.23937988]). It's not clear exactly what your data structure looks like, but that would be by far the fastest.

نصائح أخرى

I'll take a punt that you've got a 2D numpy array (self.features) of (coordinate pairs?) and you want to format each row (position?), eg:

for pair in self.features: 
    print '{0}, {1}'.format(*pair)

As in your example. I think that answers your question.

>>> x = "[array([[ 1948.97753906, 1058.23937988]], dtype=float32)]"
>>> print x.split("[[")[1].split("]]")[0].replace(",","")

If the format is always the same, that is it always starts with "[array([[" and always ends with "]], dtype=float32)" you should use a slice instead.

final = str(self.lostfeatures)[len('[array([[ '):-len(']], dtype=float32)')]

I'd probably recommend a regex for this use case

import re

ptrn = re.compile(r'((?:\d+(?:\.\d+)?, ?)+(?:\d+(?:\.\d+)?))'

x = "[array([[ 1948.97753906, 1058.23937988]], dtype=float32)]"
print ptrn.search(x).group(1)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top