1

I have the following data frame:

   product    price 
0     a       100000     
1     b       2000000     
2     c       30000000000

and I would like to convert the price column to the following format

   product    price 
0     a       100K     
1     b       2M     
2     c       30B
Mustard Tiger
  • 3,520
  • 8
  • 43
  • 68
  • Does this answer your question? [How to convert a values like 1225002 to 1.2M in a column using pandas?](https://stackoverflow.com/questions/67556201/how-to-convert-a-values-like-1225002-to-1-2m-in-a-column-using-pandas) – ThePyGuy May 21 '21 at 01:33

3 Answers3

2

Extending the answer from how-to-convert-a-values-like-1225002-to-1-2m-in-a-column-using-pandas , You can use apply alongwith lambda and f-string to get the required output

df['price']=df['price'].apply(lambda x: f'{x//1000000000}B' if x/1000000000>=1 else f'{x//1000000}M' if x/1000000>=1 else f'{int(x//1000)}K' if x/10000>=1 else f'{x}')

OUTPUT:

    product price
0      a    100K
1      b    2M
2      c    30B
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

From what my understanding we can just cover the number with accounting format, which is easy for you to read and also still keep the accuracy

df['price'].map('{:,}'.format)
0           100,000
1         2,000,000
2    30,000,000,000
Name: price, dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234
0

Look here: formatting long numbers as strings in python

def human_format(num):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    # add more suffixes if you need them
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
df['price'] = df['price'].apply(human_format)
Pierre S
  • 16
  • 4