簡體   English   中英

從一列字符串中提取浮點數並四舍五入到小數點后兩位

[英]Extract floats from a column of strings and round to 2 decimal places

如果我有一列中有值的數據框

4.5678
5
7.987.998

我只想提取小數點后2個值的數據

4.56
5
7.98

數據存儲為字符串。 任何幫助將不勝感激。 謝謝 !

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不能是您的預期輸出所描述的整數,否則將導致混合類型,並且通常不建議使用。

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個或更多,我們將返回整個第一個字符串,一個句點以及第二個字符串的前2個字符
  4. 如果沒有,我們只返回原始輸入。
str = "7.987.998"
ind = str.find('.')
if ind > 0:
  res = str[:ind+3]

另一種熊貓方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM