Home > other >  Convert numbers in millions and thousands to string format
Convert numbers in millions and thousands to string format

Time:09-02

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

CodePudding user response:

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

CodePudding user response:


  • 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

  • Related