1

I have a column in my pandas dataframe:

df = pd.DataFrame([[3000000, 2500000, 1800000, 800000, 500000]], columns=['Market value'])

I want to convert the numbers in this column to a format with millions and hundred thousands, for example:

  • 3000000 -> €3M
  • 2500000 -> €2.5M
  • 1800000 -> €1.8M
  • 800000 -> €800K
  • 500000 -> €500K

This is my attempt so far:

df['Market Value'] = np.select(condlist = [(df['Market value']/1000) >= 1000],
                               choicelist = ['€'+(df['Market value'].astype(float)/1000000).astype(int).astype(str) + 'M'],
                               default = '€'+(df['Market value'].astype(float)/1000).astype(int).astype(str) + 'K')

This produces the output:

  • 3000000 -> €3M
  • 2500000 -> €2M * this needs to be €2.5M
  • 1800000 -> €1M * this needs to be €1.8M
  • 800000 -> €800K
  • 500000 -> €500K
  • 2
    Does this answer your question? [python human readable large numbers](https://stackoverflow.com/questions/3154460/python-human-readable-large-numbers) – Adam.Er8 Sep 01 '22 at 10:15

2 Answers2

3

You can apply this function to the column:

def format(num):
    if num > 1000000:
        if not num % 1000000:
            return f'€{num // 1000000}M'
        return f'€{round(num / 1000000, 1)}M'
    return f'€{num // 1000}K'

Testing:

nums_list = [3000000, 2500000, 1800000, 800000, 500000]
for num in nums_list:
    print(format(num))

Output:

€3M
€2.5M
€1.8M
€800K
€500K
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
  • That work great, thanks! I'm now trying to add this as a column to my dataframe using the code: `for num in nums_list: df['MV'] = format(num))` but this isn't working. Do you know how to do this? – codemachine Sep 01 '22 at 10:37
  • @codemachine Try this: `df['MV'] = [format(num) for num in nums_list]` – The Thonnu Sep 01 '22 at 10:38
-1

  • UPDATED

import math
def millify(n):
    n = float(n)
    millnames = ['',' K',' M',' B',' T']
    millidx = max(0,min(len(millnames)-1,
                        int(math.floor(0 if n == 0 else math.log10(abs(n))/3))))

    return '£' + str(n / 10**(3 * millidx)) + str(millnames[millidx])

df['Value in millions'] = df['Market value'].apply(lambda n: millify(n))

Output:

Market value    Value in millions
0   3000000         £3.0 M
1   2500000         £2.5 M
2   1800000         £1.8 M
3   800000          £800.0 K
4   500000          £500.0 K

For further detail you check this question python human readable large numbers

R. Baraiya
  • 1,490
  • 1
  • 4
  • 17