Light Yagmi
Light Yagmi

Reputation: 5235

Round only numeric elements of pandas.DataFrame ignoring string

I have this DataFrame:

import pandas as pd
df = pd.DataFrame({'x':["ab", "cd"],'a':[1.1111,2.2222], 'b':[2.2222,3.3333], 'c':[3.3333,4.4444]})

What is a simple way to round only numeric elements with ignoring string elements?

I've read several discussions of SO and try this, but got error.

import numpy as np
np.round(df) # => AttributeError: 'str' object has no attribute 

'rint'

I'd like to have the save DataFrame as the following:

pd.DataFrame({'x':["ab", "cd"],'a':[1.11,2.22], 'b':[2.22,3.33], 'c':[3.33,4.44]})

Upvotes: 4

Views: 6999

Answers (3)

robertzp
robertzp

Reputation: 1495

you can also simply try:

df = df.round()

Upvotes: 0

zyxue
zyxue

Reputation: 8928

>>> df[['a', 'b', 'c']] = np.round(df[['a', 'b', 'c']], 2)
>>> df
      a     b     c   x
0  1.11  2.22  3.33  ab
1  2.22  3.33  4.44  cd

Upvotes: 2

unutbu
unutbu

Reputation: 881037

You could use df.select_dtypes(include=[np.number]) to select the numeric columns of the DataFrame, use np.round to round the numeric sub-DataFrame, and df.loc to assign those values to the original DataFrame:

df = pd.DataFrame({'x':["ab", "cd"],'a':[1.1111,2.2222], 'b':[2.2222,3.3333], 
                   'c':[3.3333,4.4444]})

tmp = df.select_dtypes(include=[np.number])
df.loc[:, tmp.columns] = np.round(tmp)

yields

   a  b  c   x
0  1  2  3  ab
1  2  3  4  cd

Upvotes: 12

Related Questions