0

我有一个像

A%  B %
2   3
-   2.1
100 0
-   5

我希望输出导出的 excel 像

A%        B%
2.00%     3.00%
-         2.10%
100.00%   0.00%
-         5.00%

我有这些 A% 和 B% 通过使用以下逻辑

((df['some_values1'] / df['some_values2']) *100.00).round(2).astype(str)+('%')

但是当我将 df 的 excel 转换为 nan 并且像 2、100、0 这样的个位数没有像 2.00% 100.00% 和 0.00% 这样的两位小数时,它只有 2%、100% 和 0%,而它适用于 2.1 和其他小数位数。

提前感谢您的帮助。

4

1 回答 1

0

You can define a function that suits your needs:

def to_percent_format(p):
    if str(p).strip() != "-":
        return "{:.2%}".format(p/100)
    else:
        return p.strip() 

Indeed:

>>> to_percent_format(3)
'3.00%'
>>> to_percent_format("-")
'-'

And just apply it to your dataframe!

df.apply(to_percent_format, axis=1)
于 2020-03-19T17:15:52.530 回答