简体   繁体   中英

Format a pandas dataframe with floats and leading zeros

I have a dataframe and I need to display (not modify) the float values in a very particular way.

df = pd.DataFrame([1000.5, 100000.78, -90000, -900.4],
                  index=['row1','row2','row3','row4'],
                  columns=['amount'])
print(df)

        amount
row1    1000.50
row2  100000.78
row3  -90000.00
row4    -900.40

the whole string should be 9 characters long (including minus sign and decimal separator), the int part should have leading zeros,

the decimal part should also have filling zeros and be limited to 2 decimals

I would like to coerce this into printing (without modifying original values):

            amount
row1    001000.50
row2    100000.78
row3    -90000.00
row4    -00900.40

this is what I tried without much luck:

df['amount'].apply(lambda x: f'{x:.2f}')
df['newamount'] = df['amount'].astype(str)
width = 9
df['newamount']= df['newamount'].str.zfill(width)
print(df)

       amount   newamount
row1    1000.50     0001000.5
row2  100000.78     100000.78
row3  -90000.00     0-90000.0
row4    -900.40     000-900.4

keep in mind there are other float columns in the dataframe that should not be displayed this way

You can set the display float_format option as '{:09.2f}'.format :

pd.options.display.float_format = '{:09.2f}'.format
df    
        amount
row1 001000.50
row2 100000.78
row3 -90000.00
row4 -00900.40

But this will only change the current display. If you need to create a new column, you can use an f string:

df['newamount'] = df.amount.apply(lambda x: f'{x:09.2f}')
df    
         amount  newamount
row1    1000.50  001000.50
row2  100000.78  100000.78
row3  -90000.00  -90000.00
row4    -900.40  -00900.40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM