如何转换以百万美元为单位的熊猫列?

时间:2019-05-29 06:58:05

标签: python-3.x

我有一列叫做collection的

集合:$ 5,345,677,46836214,$ 533,316,061,“”,29200000

列值同时包含美元和不包含美元。另外,它还有NAN。我想换成百万美元

我曾经转换如下,但没有成功

df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)

得到这个错误:无法将字符串转换为浮点数:'$ 5,345,677'

请告知

1 个答案:

答案 0 :(得分:0)

您可以参考以下步骤:

1。填充NAN或空白值(空白)。您说有南,但我看到了“”。

[in ]: df['collection']
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3      
  4    29200000
[in ]: # if you have Nan, just use method `fillna` instead 
       # like df['collection'].fillna('0')
[in ]: df['collection'].replace(r'^\s*$', '0', regex=True)
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3    0
  4    29200000

2。然后将秘密数字更改为“百万美元”。

[in ]: df['collection'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in x else x)
[out]: collection
  0    $5,345,677
  1    $46,836,214
  2    $533,316,061
  3    $0
  4    $29,200,000

我希望这会有所帮助!