Change column values in a Pandas Dataframe to show numbers as Milions

Question:

i have a Pandas DataFrame

   Symbol  Name  ...  % Change      Volume
9     XXX  YYY   ...     -3.62  58792000.0
11    XXX  YYY   ...      0.18  58587000.0

I would like to change the values in ‘Volume’ to have this result

   Symbol  Name  ...  % Change      Volume
9     XXX  YYY   ...     -3.62  58.792M
11    XXX  YYY   ...      0.18  58.587M
Asked By: betanoox

||

Answers:

We can get to your desired result literally step by step, by adding a ‘$’ sign, dividing the number by 1000000, and adding the MM suffix:

df['Volume'] = '$' + (df['Volume'].astype(float)/1000000).astype(str) + 'MM'

print(df)

  Symbol Name  % Change     Volume
0    XXX  YYY    -3.620  $58.792MM
1    XXX  YYY     0.180  $58.587MM

Note that the resulting ‘Volume’ dtype will be object:

df.dtypes

Symbol       object
Name         object
% Change    float64
Volume       object
dtype: object

Happy to see if there’s a more pythonic way by others.

Answered By: sophocles

How about something simple like this –

(df.Volume/1000000).round(3).astype(str)+'M'

Just divide the column by a million, round it to 3 significant digits, convert to str, and then add an ‘M’ at the end.

Answered By: Akshay Sehgal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.