阅读背景:

百分数字符串与浮点数转换_castingA3T的博客_百分数转float

来源:互联网 
import pandas as pd
df=pd.DataFrame({'p_str':['10.33%','20.50%','56%','35.786%','99.99999%']})

#字符串去除%,转换为float,除以100
p_float=df['p_str'].str.strip('%').astype(float) / 100
#df['p_str'].map(lambda x:float(x.strip('%'))) / 100

#保留小数位数
p_float2=p_float.round(2)
#p_float2=p_float.round(decimals=2)

#小数转化为保留两位的百分数
p_str2=p_float.apply(lambda x:format(x,'.2%'))
#p_str=p_float.apply(lambda x:'%.2f%%'%x)

df['p_float']=p_float
df['p_float2']=p_float2
df['p_str2']=p_str2

In[96]: df
Out[96]: 
       p_str  p_float  p_float2   p_str2
0     10.33%  0.10330      0.10   10.33%
1     20.50%  0.20500      0.20   20.50%
2        56%  0.56000      0.56   56.00%
3    35.786%  0.35786      0.36   35.79%
4  99.99999%  1.00000      1.00  100.00%import pandas as pd
df=pd.DataFrame({'p_str':['



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: