1

I have a code that outputs a whole bunch of numbers after doing some maths on them. At one point in the code they are rounded off with numpy.rint, and in certain cases (I believe when a 9 is rounded to a 10) I end up with a trailing zero that I do not want. I have some code that looks sort-of like this

ra3n = ra3/60 * 10
ra3n = np.rint(ra3n)
ra3n = ra3n.astype(str) ##there is a good reason that this needs to be a string

I need all of the resulting ra3n to be 5 characters long, but occasionally one pops out as 6 characters long. How would I format this properly? Keep in mind I'm a total python noob, so I might need it spelled out for me =)

EDIT:

Here's my output:

00244-2451
00244-2702
00278-0629
00286-1614
00295-1101
002910-0546
00303+0711
00305+2246
00348+2604
003410+0423
00355-0204
00359+1236
00360-0931
00386-1210

The instances where there are six digits instead of 5 in the first half of the string are the erroneous ones; those trailing zeroes should not be there.

2
  • ra3n.astype('|S5')? Commented May 10, 2016 at 19:38
  • Attempted this, but it didn't work. Commented May 10, 2016 at 19:57

2 Answers 2

2

ra3n = ra3n[:-1] if ra3n[-1] == '0' else ra3n

There's probably a better solution, but I'm not sure I really understand your issue without seeing some output.

Sign up to request clarification or add additional context in comments.

1 Comment

Edited with my output.
2

You change the type of ra3n, which is poor programming practice. Try this.

ra3n = format(ra3/60.*10., '5f')[:5]

This gives exactly five characters. Note that if the string would usually be six characters long, this cuts off the last character, for good or for bad. Note also that I included decimal points in the 60 and 10 numbers: this guarantees that floating-point division will be used, rather than integer division if this is done in Python 2.

6 Comments

Okay, cool. I'm having a problem though: I use numpy.loadtxt to import my arrays, and I have to import as str because there are a bunch of different data types. So I then use ra3 = ra3.astype(float) just before the line you suggested, but it's giving me Unknown format code 'f' for object of type 'str' for the line you gave me.
@uhurulol: Oops, I had a typo: I wrote r13 rather than ra3. Try it now. Or perhaps use format(float(ra3)/60.*10., '5f')[:5].
I got that typo don't worry, but it's still not working ><
The second suggestion you made gives this error: TypeError: only length-1 arrays can be converted to Python scalars
@uhurulol: I don't know numpy, so I am not sure what is happening, I can only guess. What exactly is the type of ra3?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.