熊猫,如何将数字转换为货币格式“ XXX,XXX.xx $”

时间:2020-06-25 23:13:35

标签: python pandas

我正在尝试将数字XXXXXX.xx转换为货币格式“ XXX,XXX.xx $”

案例1和#2,使用熊猫数据框:

      Amount    Currency #1   ($) Currency #2
0    1000000      1,000,000       1,000,000 $
1   97320.25      97,320.25       97,320.25 $
2  9000000.1   9,000,000.10    9,000,000.10 $

就代码简单而言,哪种方法最适合此任务?

df['Currency #1'] = df['Amount'].ToString("###,###,###.00") ??
df['($) Currency #2'] = df['Amount'].apply(lambda x...??
df['($) Currency #2'] = df['Amount'].SomeInternalFunction() ??

1 个答案:

答案 0 :(得分:2)

您可以使用.map('{:,}'.format)

In [191]: df['Amount'].map('{:,}'.format)
Out[191]: 
0    1,000,000.0
1      97,320.25
2    9,000,000.1
Name: Amount, dtype: object

In [192]: df['Amount'].map('{:,} $'.format)
Out[192]: 
0    1,000,000.0 $
1      97,320.25 $
2    9,000,000.1 $
Name: Amount, dtype: object

In [193]: df['Currency #1'] = df['Amount'].map('{:,}'.format)

In [194]: df['Currency #2'] = df['Amount'].map('{:,} $'.format)

In [195]: df
Out[195]: 
       Amount  Currency #1    Currency #2
0  1000000.00  1,000,000.0  1,000,000.0 $
1    97320.25    97,320.25    97,320.25 $
2  9000000.10  9,000,000.1  9,000,000.1 $