繁体   English   中英

如何获得小数的小数部分的第一位数字?

[英]How to get the first digit of the fractional part of a decimal number?

在我的大熊猫中,数据是这样的:
在此处输入图片说明

(原始数据类似于2.1, 3.7, 5.6后面没有0。)

我想查看小数部分第一位的分布。 (即6 for 4.6 )。 我该怎么做?

我考虑过15.1 % 1 ,但它返回0.09999999999999964

对于正数,可以先使用乘法,然后再取模。

x = 15.6
x *= 10 # 156
x %= 10 # 6

如果它们是负数,

def get(x):
    return (x * 10) % 10
x = - 15.6
print get(abs(x))

戳建议使用一种更清洁的方法。

abs(x * 10) % 10

如果您有一个称为df的数据框,则可以将其封闭为:

df.apply( lambda x: abs(x * 10) % 10 )

您可以尝试:

int(str(x).split('.')[1][0])

这将转换为字符串,分割为。 并取第二部分的第一个字符,然后将其返回为整数。 之所以得到一个奇怪的值,是因为0.1是二进制数中的非理性数字。

您还可以使用:

int(x * 10.0) % 10

这将确保您有一个整数,(您可能还需要使用math.round )。

举个例子:

>>> pf = pandas.DataFrame([0.5, 4.6, 7.2, 9.8, 36.0])
>>> pf
      0
0   0.5
1   4.6
2   7.2
3   9.8
4  36.0
>>> pf[0]
0     0.5
1     4.6
2     7.2
3     9.8
4    36.0
Name: 0, dtype: float64
>>> pf.apply(lambda x: int(x[0]*10.0)%10)
0    5
dtype: int64
>>> pf.apply(lambda x: int(x[0]*10.0)%10, 1)
0    5
1    6
2    2
3    8
4    0
dtype: int64
>>>

在测试-ve数字时:

>>> pf = pandas.DataFrame([0.5, 4.6, 7.2, -9.8, 36.0])
>>> df = pf.apply(lambda x: int(x[0]*10.0)%10, 1)
>>> df
0    5
1    6
2    2
3    2
4    0
dtype: int64
>>> df = pf.apply(lambda x: int(abs(x[0])*10.0)%10, 1)
>>> df
0    5
1    6
2    2
3    8
4    0
dtype: int64
>>>

因此,我们的最终答案是:

pf.apply(lambda x: int(abs(x[0])*10.0)%10, 1)

我也尝试过字符串方法:

>>> pf.apply(lambda x:int(str(x[0]).split('.')[1][0]), 1)
0    5
1    6
2    2
3    8
4    0
dtype: int64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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