[英]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.