我最初在string
中有以下列,我将它们转换为float
用于某些计算目的。
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.222222222222%
251.48% 23.999999999999%
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100
Growth1 Growth2
43.6546 1.2448
0.4529 0.02222222222222
2.5148 0.23999999999999
但是,它们是十进制格式,我希望它们以%格式显示。但我不能在以下行之后添加{:,.2%}'.format
:
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100(formatters=[{:,.2%}'.format])
有什么方法可以将float
保留在% format
中并用最少的代码(如1或2行)将其四舍五入到小数点后两位?谢谢。
期望的输出:
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.22%
251.48% 24.00% # or 23.99%, no big deal
答案 0 :(得分:1)
看起来您用于format
的参数不正确。它应该是{:,.2f}
和%outside:
示例:
>>> "{:,.2f}%".format(4365.46)
'4,365.46%'
答案 1 :(得分:1)
df['Growth1'] = pd.Series(['{0:.2f}%'.format(val * 100) for val in df['Growth1']], index = df.index)
“Growth2”栏目相同。
注意:如果您想保留原始列,只需将新名称命名为“Growth1”
答案 2 :(得分:1)
也许正在使用pandas style?
var msg="";
var DOMstring = {
firstName:'uname',
lastName:'ulastname',
userName:'uuname',
contact:'contact',
email:'email',
pass1:'pass-1',
pass2:'pass-2',
submit:'submit-btn'
}
function validate(){
var status = false;
var firstName = document.getElementById(DOMstring.firstName).value;
status = checkText(firstName,'First Name');
var lastName = document.getElementById(DOMstring.lastName).value;
status = checkText(lastName,'Last Name');
var userName = document.getElementById(DOMstring.userName).value;
status=checkText(userName,'Username');
var contact = document.getElementById(DOMstring.contact).value;
status = checkNumber(contact);
var pass1 = document.getElementById(DOMstring.pass1).value;
status = checkPass(pass1);
var pass2 = document.getElementById(DOMstring.pass2).value;
status = comparePass(pass1,pass2);
if(status == true){
alert("successfully created an account");
return true;
}else{
alert("Please consider the following error messages<br>"+msg);
return false;
}
}
function checkText(DOMname,name){
var ckeck_text = /^[A-Za-z]$/;
if(!check_text.test(DOMname)){
msg += name + ' cannot contain numbers or special character.<br>';
return false;
}
return true;
}
function checkNumber(DOMnumber){
var check_number = /^[0-9]{10}$/;
if(!check_number.test(DOMnumber)){
msg += 'Number contains 10 digit only<br>';
return false;
}
return true;
}
function checkPass(DOMpass1){
var check_pass = /^(?=.*[\d])(?=.*[!@#$%^&*])[\w!@#$%^&*]{8,16}$/;
if(!check_pass.test(DOMpass1)){
msg += 'Password field should contain alphanumeric values and special character<br> and should be in range from 8 to 16<br>';
return false;
}
return true;
}
function comparePass(DOMpass1,DOMpass2){
if(!DOMpass1 === DOMpass2){
msg += 'Both password does not match<br>';
return false;
}
return true;
}
当您通过此次调用显示返回的对象时,就像您通常使用数据框一样,它会以您要求的方式格式化您的列。