[英]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
我將分解這里發生的事情:
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.