gpt4 book ai didi

python - 从十进制格式的字符串中提取基数和指数以 10 表示

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:39 25 4
gpt4 key购买 nike

我正在寻找一个采用十进制格式字符串的函数的高效 Python 实现,例如

2.05000
200
0.012

并返回两个整数的元组,表示以 base-10 浮点格式输入的有效数字和指数,例如

(205,-2)
(2,2)
(12,-3)

列表理解将是一个很好的奖励。

我有一种直觉,认为存在一种有效的(并且可能是 Pythonic 的)方法来做到这一点,但它让我望而却步......


应用于 Pandas 的解决方案

import pandas as pd
import numpy as np
ser1 = pd.Series(['2.05000', '- 2.05000', '00 205', '-205', '-0', '-0.0', '0.00205', '0', np.nan])

ser1 = ser1.str.replace(' ', '')
parts = ser1.str.split('.').apply(pd.Series)

# remove all white spaces
# strip leading zeros (even those after a minus sign)
parts.ix[:,0] = '-'*parts.ix[:,0].str.startswith('-') + parts.ix[:,0].str.lstrip('-').str.lstrip('0')

parts.ix[:,1] = parts.ix[:,1].fillna('') # fill non-existamt decimal places
exponents = -parts.ix[:,1].str.len()
parts.ix[:,0] += parts.ix[:,1] # append decimal places to digit before decimal point

parts.ix[:,1] = parts.ix[:,0].str.rstrip('0') # strip following zeros

exponents += parts.ix[:,0].str.len() - parts.ix[:,1].str.len()

parts.ix[:,1][(parts.ix[:,1] == '') | (parts.ix[:,1] == '-')] = '0'
significands = parts.ix[:,1].astype(float)

df2 = pd.DataFrame({'exponent': exponents, 'significand': significands})
df2

输入:

0      2.05000
1 - 2.05000
2 00 205
3 -205
4 -0
5 -0.0
6 0.00205
7 0
8 NaN
dtype: object

输出:

   exponent  significand
0 -2 205
1 -2 -205
2 0 205
3 0 -205
4 0 0
5 0 0
6 -5 205
7 0 0
8 NaN NaN

[9 rows x 2 columns]

最佳答案

看看 decimal.Decimal:

>>> from decimal import Decimal
>>> s = '2.05000'
>>> x = Decimal(s)
>>> x
Decimal('2.05000')
>>> x.as_tuple()
DecimalTuple(sign=0, digits=(2, 0, 5, 0, 0, 0), exponent=-5)

几乎可以满足您的需求,只需将 DecimalTuple 转换为您想要的格式,例如:

>>> t = Decimal('2.05000').as_tuple()
>>> (''.join(str(x) for i,x in enumerate(t.digits) if any(t.digits[i:])),
... t.exponent + sum(1 for i,x in enumerate(t.digits) if not
... any (t.digits[i:])))
('205', -2)

只是一个草图,但满足你的三个测试用例。

您可能希望在处理.as_tuple() 之前.normalize() 您的Decimal(感谢@georg),这需要注意尾随零。这样,您就不需要做那么多格式设置:

>>> Decimal('2.05000').normalize().as_tuple()
DecimalTuple(sign=0, digits=(2, 0, 5), exponent=-2)

所以你的函数可以写成:

>>> def decimal_str_to_sci_tuple(s):
... t = Decimal(s).normalize().as_tuple()
... return (int(''.join(map(str,t.digits))), t.exponent)
...
>>> decimal_str_to_sci_tuple('2.05000')
(205, -2)
>>> decimal_str_to_sci_tuple('200')
(2, 2)
>>> decimal_str_to_sci_tuple('0.012')
(12, -3)

(尽管支持负数时一定要添加 t.sign)。

关于python - 从十进制格式的字符串中提取基数和指数以 10 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26889711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com