Home > Blockchain >  How to format the rows of only selected columns of df
How to format the rows of only selected columns of df

Time:10-19

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.

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'?

CodePudding user response:

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

CodePudding user response:

Maybe something along the line:

df[['B', 'C']].apply(lambda x: np.around(x, decimals=2), axis=0)

for two decimal digits....

CodePudding user response:

new_df = df.round({"B":0,"C":0})

You can change dictionary values for nay number of decimal places for each column

  • Related