Mustard Tiger
Mustard Tiger

Reputation: 3671

Pandas format large numbers

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

Upvotes: 1

Views: 1053

Answers (3)

Pierre S
Pierre S

Reputation: 16

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)

Upvotes: 0

ThePyGuy
ThePyGuy

Reputation: 18406

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

Upvotes: 2

BENY
BENY

Reputation: 323226

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

Upvotes: 0

Related Questions