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:
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:
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