Issue
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]})
Solution
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
Answered By - unutbu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.