从一列字符串中提取浮点数并舍入到小数点后两位

时间:2017-10-03 21:08:30

标签: python pandas floating-point

如果我的数据框中包含值

4.5678
5
7.987.998

我想在小数

之后仅提取2个值的数据
4.56
5
7.98

数据存储为字符串。任何帮助将不胜感激。谢谢 !

4 个答案:

答案 0 :(得分:2)

print(s) 
0       4.5678
1            5
2    7.987.998
Name: 0, dtype: object

print(type(s))
Out[152]: pandas.core.series.Series

使用str.extract + round

r = s.str.extract('(\d+(?:\.\d+)?)', \
           expand=False).astype(float).round(2)
print(r)
0    4.57
1    5.00
2    7.99
Name: 0, dtype: float64

不幸的是,5不能像您预期的输出所描述的那样是一个整数,这会导致混合类型并且通常不鼓励。

答案 1 :(得分:0)

def get_two_spaces(input):
    input_list = input.split('.')
    if len(input_list) >= 2:
        return input_list[0] + '.' + input_list[1][:2]
    return input

我会分解这里发生的事情:

  1. 我们将字符串拆分为句点字符周围的字符串列表。
  2. 我们看到该列表中有多少项:
  3. 如果有2个或更多,我们返回整个第一个字符串,一个句点,以及第二个字符串的前两个字符
  4. 如果没有,我们只返回原始输入。

答案 2 :(得分:0)

str = "7.987.998"
ind = str.find('.')
if ind > 0:
  res = str[:ind+3]

答案 3 :(得分:0)

另一个 pandas 方法:

import pandas as pd

df = pd.DataFrame(['4.5678','5','7.987.998'], columns=['A'])
s = df['A'].replace(to_replace='^(\d+\.\d+)\.\d+', value=r'\1', regex=True)\
    .astype('float').map('{:,.2f}'.format)

print(s)

输出:

0    4.57
1    5.00
2    7.99
Name: A, dtype: object
相关问题