简体   繁体   中英

In numbers with range of values, how to move the decimal point left until a single digit integer remains in Python

I'd like to take a number like: 12345678 and turn it into 1.2345678, leaving only a single digit integer and whatever decimal.

Multiplying 12345678 by 0.0000001 works for the above example, but not if the number is 1234. The numbers change so a static multiplier will not work.

Is there a method available that would help? Bonus if it can be done within a pandas dataframe.

You can use np.log10 and astype(int) to find the correct power:

df['number'] /= 10**(np.log10(df['number']).astype(int))

Output:

     number
0  1.234568
1  1.234000

Take below dataframe for example:

In [1192]: df 
Out[1192]: 
          a
0  12345678
1      1234

You can use Python's basic string slicing :

In [1190]: df = df['a'].astype(str).str[0] + '.' + df['a'].astype(str).str[1:]

In [1191]: df
Out[1191]: 
             a
0    1.2345678
1        1.234
Name: a, dtype: object

I can think on two ways.

A= Str (xxxxxxx)

B = float (A[0]+”.”+A[1:len(A)])

Another way:

A=A / pow(10,len(str(A)-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM