Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numbers in millions and thousands to string format

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
like image 359
codemachine Avatar asked Oct 18 '25 15:10

codemachine


1 Answers

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
like image 170
The Thonnu Avatar answered Oct 21 '25 05:10

The Thonnu