0

I want to convert the numpy array ['800' '0' '0.3048' '71.3' '0.00266337'] to float form with the sigfigs shown in the strings.

When I tried (with help from this answer X_new = X_tr.astype(float) I got [8.00000e+02 0.00000e+00 3.04800e-01 7.13000e+01 2.66337e-03] I don't want to see the full floating point form. Is there a way for it to format the float the way it was in the string? I would prefer if I didn't have to round to the decimal I want for each specific column case.

3 Answers3

1

This is a list task. Start with a utility function that returns an integer or float:

In [392]: def foo(astr):
     ...:     try:
     ...:         res = int(astr)
     ...:     except ValueError:
     ...:         res = float(astr)
     ...:     return res
     ...: 

Apply it to a list of strings:

In [393]: alist = ['800', '0', '0.3048', '71.3', '0.00266337']

In [394]: [foo(i) for i in alist]
Out[394]: [800, 0, 0.3048, 71.3, 0.00266337]

If you must get an array, make it object dtype:

In [395]: np.array([foo(i) for i in alist], dtype=object)
Out[395]: array([800, 0, 0.3048, 71.3, 0.00266337], dtype=object)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

You cannot get the desired result using a numpy array because numpy arrays must be all one datatype. In your example, the first two numbers would need to be integers while the rest are floats. If you are okay with a python list, then you can use the round function and change the decimal argument for each number.

def get_decimals(n):
    if "." not in n:
        return None
    after_decimal = n.split(".")[1]
    return len(after_decimal)

a = ['800', '0', '0.3048', '71.3', '0.00266337']
decimals = [get_decimals(_a) for _a in a]
a_float = [float(_a) for _a in a]
a_rounded = [round(_a, decimal) for _a, decimal in zip(a_float, decimals)]
print(a_rounded)        # [800, 0, 0.3048, 71.3, 0.00266337]
jared
  • 4,165
  • 1
  • 8
  • 31
0

Not precisely what you wanted (800.0 instead of 800), but the easiest code would be:

list_of_floats = [float(item) for item in ['800', '0', '0.3048', '71.3', '0.00266337']]
print(list_of_floats)
[800.0, 0.0, 0.3048, 71.3, 0.00266337]
dankal444
  • 3,172
  • 1
  • 23
  • 35