在pandas中将某些浮动数据框列设置为百分比 [英] Format certain floating dataframe columns into percentage in pandas
问题描述
df
,有什么方法来格式化 var1
和 var2 转换为2位小数, var3
转换为百分比。
var1 var2 var3
id
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
里面的数字不乘以100,例如-0.0057 = -0.57%。
解决方案使用循环函数替换值,并设置百分比数字的字符串表示形式:
$ b $ df ['var2'] = pd.Series([round(val,2)for val in df ['var2' ],index = df.index])
df ['var3'] = pd.Series([{0:.2f}%)格式(val * 100)for df ['var3'] ],index = df.index)
循环函数将浮点数乘以十进制数作为函数的第二个参数提供的位置。
字符串格式允许您根据需要表示数字。您可以通过更改 f
之前的数字来更改小数位数。
p。我不确定你的百分比数字是否已经乘以100.如果他们已经清楚地知道你将要改变显示的小数位数,并去除百乘。
I am trying to write a paper in IPython notebook, but encountered some issues with display format. Say I have following dataframe df
, is there any way to format var1
and var2
into 2 digit decimals and var3
into percentages.
var1 var2 var3
id
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
The numbers inside are not multiplied by 100, e.g. -0.0057=-0.57%.
解决方案 replace the values using the round function, and format the string representation of the percentage numbers:
df['var2'] = pd.Series([round(val, 2) for val in df['var2'], index = df.index])
df['var3'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['var3']], index = df.index)
The round function rounds a floating point number to the number of decimal places provided as second argument to the function.
String formatting allows you to represent the numbers as you wish. You can change the number of decimal places shown by changing the number before the f
.
p.s. I was not sure if your 'percentage' numbers had already been multiplied by 100. If they have then clearly you will want to change the number of decimals displayed, and remove the hundred multiplication.
这篇关于在pandas中将某些浮动数据框列设置为百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!