结合两种格式

时间:2019-08-30 11:15:48

标签: python pandas

我正在格式化数据框。我需要做千位分隔符和小数点。问题是当我将它们组合在一起时,只有最后一个有效。我想很多人可能会有同样的困惑,因为我在Google上搜索了很多,却找不到任何东西。

我尝试使用.map(lambda x:('%.2f')%x and format(x,','))将两种必需的格式组合在一起,但是只有最后一种有效。

DF_T_1_EQUITY_CHANGE_Summary_ADE['Sum of EQUITY_CHANGE'].map(lambda x:format(x,',') and ('%.2f')%x)

DF_T_1_EQUITY_CHANGE_Summary_ADE['Sum of EQUITY_CHANGE'].map(lambda x:('%.2f')%x and format(x,','))

第一个结果是:

0    -2905.22
1    -6574.62
2     -360.86
3    -3431.95
Name: Sum of EQUITY_CHANGE, dtype: object

第二个结果是:

0    -2,905.2200000000003
1               -6,574.62
2                 -360.86
3    -3,431.9500000000003
Name: Sum of EQUITY_CHANGE, dtype: object

我尝试了一种新方法,方法是使用

DF_T_1_EQUITY_CHANGE_Summary_ADE.to_string(formatters={'style1': '${:,.2f}'.format})

结果是:

Row Labels  Sum of EQUITY_CHANGE    Sum of TRUE_PROFIT  Sum of total_cost   Sum of FOREX VOL    Sum of BULLION VOL  Oil Sum of CFD VOL  Sum of BITCOIN VOL  Sum of DEPOSIT  Sum of WITHDRAW Sum of IN/OUT
0   ADE A BOOK USD  -2,905.2200000000003    638.09  134.83  15.590000000000002  2.76    0.0 0.0 0   0.0 0.0 0.0
1   ADE B BOOK USD  -6,574.62   -1,179.3299999999997    983.2099999999999   21.819999999999997  30.979999999999993  72.02   0.0 0   8,166.9 0.0 8,166.9
2   ADE A BOOK AUD  -360.86 235.39  64.44   5.369999999999999   0.0 0.0 0.0 0   700.0   0.0 700.0
3   ADE B BOOK AUD  -3,431.9500000000003    190.66  88.42999999999999   11.88   3.14    0.03    2.0 0   20,700.0    -30,000.0   -9,300.0

结果使我感到困惑,因为我设置了无效的.2f格式。

2 个答案:

答案 0 :(得分:0)

map方法不就地;它不会修改Series,但会返回一个新的Series。 因此,只需将地图结果替换为旧地​​图即可。

此处文档: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html

答案 1 :(得分:0)

使用迷你字符串格式化程序,您可以添加逗号,并使用f'{:,.2f}'将小数位设置为2位。

import pandas as pd

df = pd.DataFrame({'EQUITY_CHANGE': [-2905.219262257907,
  -6574.619531995241,
  -360.85959369471186,
  -3431.9499712161164]}
)

df.EQUITY_CHANGE.apply(lambda x: f'{x:,.2f}')
# returns:
0    -2,905.22
1    -6,574.62
2      -360.86
3    -3,431.95
Name: EQUITY_CHANGE, dtype: object
相关问题