问题描述
我有以下df:
table:
A B C D
0 0.000000 0.000000 -0.002520 -0.002520
1 0.209772 0.016262 0.003411 0.024343
2 -0.006474 -0.000152 0.000152 0.000000
真正的df大约有12列40行.
The real df has about 12 columns and 40 rows.
我想更改其格式:
我面临的问题是如何将一种格式应用于某些列,而将另一种格式应用于其他列.通常,我通常将格式应用于整个df,而不是单独应用于列.
The problem I am facing is how can I apply a format to some columns and a different format to other columns . Normally I use to apply formats to entire dfs but not to columns individually.
所需的输出将是这样的:
The desired output would be something like this:
table:
A B C D
0 0.00% 0.000% -0.000% -0.00%
1 0.20% 0.067% 0.001% 0.43%
2 -0.00% -0.000% 0.015% 0.00%
在所需的输出中,您可以看到A和D的列四舍五入为2个有效数字,B和C的列四舍五入为3个有效数字,并将%添加到所有这些数字中
As you can see in the desired output columns A and D are rounded to 2 signif figures and B and C are rounded to 3 signif figures and added the % to all of them
这是我尝试过但没有起作用的:
this is what I have tried and did not work:
format_AD = "{0:.2f}%".format
format_BC= "{0:.3f}%".format
format_changeAD=[table.loc[:,['A','D']]]
format_changeBC=[table.loc[:,['B','C']]]
format_changeAD.apply(format_AD)
format_changeBC.apply(format_BC)
return table
推荐答案
您可以使用 applymap
并将输出分配回去:
You can use applymap
and assign output back:
table[['A','D']]= table[['A','D']].applymap(format_AD)
table[['B','C']]= table[['B','C']].applymap(format_BC)
print (table)
A B C D
0 0.00% 0.000% -0.003% -0.00%
1 0.21% 0.016% 0.003% 0.02%
2 -0.01% -0.000% 0.000% 0.00%
这篇关于将不同的格式应用于不同的列数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!