[Python] Convert numbers in millions and thousands to string format

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página