0

I have a column earnings in int form, and want to convert to millions of dollars. At the moment i'm getting

KeyError on 'earnings'

using below formula, How do i fix this.

biopics = biopics['earnings'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in x else x)
Shadow Walker
  • 979
  • 5
  • 27
  • 51
  • Can you show us your Dataframe or error is reflected may be your Dataframe does not contain column named earnings – Bhavya Parikh May 23 '21 at 10:00
  • This may mean that your dataframe does not contain the "earnings" column. Check your dataframe, your spelling etc... – Houssam Metni May 23 '21 at 10:01
  • See if this can help [Convert 1225002 to 1.2m in pandas column](https://stackoverflow.com/questions/67556201/how-to-convert-a-values-like-1225002-to-1-2m-in-a-column-using-pandas/67556302#67556302) – ThePyGuy May 23 '21 at 10:04

1 Answers1

0
  1. To convert int to dollar currency format, try doing this:
biopics['earnings'] = biopics['earnings'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in str(x) else x)

This will convert 10000 to $10,000

  1. To convert it to M, K dollar format:
biopics['earnings'] = biopics['earnings'].apply(lambda x: f'${x/1000000:.1f}M' if x/1000000>=1 else f'${int(x/1000)}K' if x/10000>=1 else f'${x}')

This will convert 10000000 to $10M and 10000 to $10K