Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format the rows of only selected columns of df

I have the following df:

df = pd.DataFrame({'A': ['foo', 'bar'],
                   'B': [134.532, 543.009],
                   'C': [1.98, 0.9],
                   'D': [300.99, 7000.89]

})
Output:

     A        B     C
0  foo  134.532  1.98
1  bar  543.009  0.90

I want to format/round every row of the columns B and C to have 0 decimal places.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I do not want to change the original df to contain only these columns, that is, the formatting of the others needs to stay.

And I need to select the columns by their index because I have many columns, that I can’t manually select by manually typing their headers.

I have tried:

new_df = df.iloc[:, 1:].map('{:,.0f}'.format)

But Im getting: AttributeError: 'DataFrame' object has no attribute 'map'. Did you mean: 'mad'?

>Solution :

to round the value i.e., .5 will round up and then drop the decimal (0) part

df[['B','C']]=df[['B','C']].round(0).astype(int)
df
    B   C
0   135     2
1   543     1

using index location

# choose all rows, and columns from 1 and onward
df.iloc[:,1:]=df.iloc[:,1:].round(0).astype(int)
df
    A   B   C
0   foo     135     2
1   bar     543     1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading