I Have series of float numbers - [0.1, 0.01, 0.0001, 0.000123]. How can i get "longest" float (not a minimum!) - 0.000123?
CodePudding user response:
Convert the float numbers to string
and then use len
with pandas.Series.argmax
:
import pandas as pd
s = pd.Series([0.1, 0.01, 0.0001, 0.000123])
float_length = s.astype(str).map(len)
out = s.loc[float_length.argmax()]
# Output :
print(out)
0.000123
CodePudding user response:
try:
import numpy as np
# take a list/numpy array of floats and return the longest float
def get_longest(x):
idx = sorted([(n, len(str(i).split('.')[-1])) for n, i in enumerate(x)], key=lambda x: x[1])[-1][0]
return x[idx]
a = [0.000123, 0.1, 0.01, 0.0001]
print(get_longest(a))
# 0.000123
print(get_longest(np.array(a)))
# 0.000123
b = [0.1, 0.01, 0.0001, 0.000123]
print(get_longest(b))
# 0.000123
if you have scientific notation (float with very long Decimal parts
) in your list/np array:
def get_longest(x):
x = [str(np.format_float_positional(i, trim='-')) for i in x]
idx = sorted([(n, len(i.split('.')[-1])) for n, i in enumerate(x)], key=lambda x: x[1])[-1][0]
return x[idx]
c = [9e-09, 6.5e-20, 0.1, 0.01] # --> [0.000000009, 0.000000000000000000065, 0.1, 0.01]
print(get_longest(np.array(c)))
# 0.000000000000000000065
print(get_longest(c))
# 0.000000000000000000065